<!-- 需要动态生成的-->
//目标页面的home
var taskId = 1001;
var listType = '1', detailType = '2';
var homeUrl = "http://localhost:8085/";
var targetSiteHomeUrl = '';

function getTargetSiteHomeUrl() {
    return targetSiteHomeUrl;
}

$.fn.ownText = function () {
    return this.eq(0).contents().filter(function () {
        return 3 === this.nodeType
    }).map(function () {
        return this.nodeValue
    }).get().join("")
};

$(document).ready(function () {
    pageType = $('#pageType').val();
    taskId = $('#taskId').val();
    $('#datetimepickerMinRdtStr').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $('#datetimepickerMaxRdtStr').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $("input[name=randType]").on("change", function () {
        changeRandTypeShow($(this).attr("data-show")),
            changeValueType(),
            resetFieldIconCurr();
    }),
        $("select[name=valueType]").on("change", function () {
            var e = $("#valueType").val();
            "attr" == e ? $(".ts-attrValue-div").css("display", "block") : $(".ts-attrValue-div").css("display", "none");
            if ("random" == e) {
                $('.ts-randomConfig').css("display", "");
                $('.ts-commonConfig').removeClass("layui-this") & $('#commonConfig').removeClass("layui-show") & $('.ts-randomConfig').addClass("layui-this") & $('#randomConfig').addClass("layui-show");
            } else {
                $('.ts-randomConfig').css("display", "none");
            }
            var t = "html" == e;
            dealCheckBox("useHtml", t),
                currFieldConfig.useHtml = t;
            if ("attr" != e && currFieldConfig.useLink) {
                dealCheckBox("useLink", false);
                currFieldConfig.useLink = false;
            }
            currFieldConfig.valueType = e,
                showFieldFinalData()
        }),
        $("input[name=dela]").on("change", function () {
            "2" == $(this).val() ? setCheckBoxById("dela-keeptxt", "2") : dealCheckBox("dela-keeptxt", !1)
        }),
        $("input[name=dela]").on("change", function () {
            "2" == $(this).val() && (setCheckBoxById("dela-keeptxt", "2"),
                dealCheckBox("dela", !1),
                currFieldConfig.dela = 0)
        });
    var copyrightTxt = "<p>本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理</p>";
    $(".ts-fill-copyright").on("click", function () {
        var e = $(this).attr("data");
        $("#tailTxt").val(e),
            currFieldConfig.tailTxt = $("#tailTxt").val()
    }),
        $(".ts-check-all-htmlTags").click(function () {
            this.checked ? $("input[name='htmlEleGroup']:checkbox", $(".ts-htmlTag-items-div")).each(function () {
                $(this).prop("checked", !0)
            }) : $("input[name='htmlEleGroup']:checkbox", $(".ts-htmlTag-items-div")).each(function () {
                $(this).prop("checked", !1)
            })
        });
    var tjDefaultHtmlTag = ["a", "p", "img", "font", "span", "br", "hr", "tjtag_hx", "tjtag_strong", "tjtag_ul", "tjtag_dl", "tjtag_em", "tjtag_code", "tjtag_subp", "tjtag_block", "tjtag_small", "strike", "tjtag_table"];
    $(".ts-htmlTag-reset").click(function () {
        bootbox.confirm("确定重置为默认HTML标签吗?", function (e) {
            e && initHtmlTags(tjDefaultHtmlTag.join(","))
        })
    });

    function setCheckBoxById(e, t) {
        t ? $("#" + e).prop("checked", !0) : $("#" + e).attr("checked", !1)
    }

    function e(e) {
        var t = e.attr("useHtml")
            , i = !(!t || "1" != t);
        addNewRowCommon(e.attr("fieldValue"), i)
    }

    function t(e, t) {
        var i = homeUrl + "/task/extrator/" + e + "/" + taskId;
        t && (i = i + "?testUrl=" + i),
            window.open(i)
    }

    function i() {
        $("#pageUrl").autocomplete({
            minLength: 0,
            source: function (e, t) {
                new RegExp($.ui.autocomplete.escapeRegex(e.term), "i");
                t($.map(m, function (t) {
                    var i = t;
                    if (!e.term || i)
                        return {
                            label: i.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(e.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"),
                            value: i,
                            option: this
                        }
                }))
            },
            select: function (e, t) {
                var i = t.item.value;
                $(this).val(i),
                    loadUrl()
            }
        }).focus(function () {
            $(this).autocomplete("search")
        })
    }

    function n() {
        // var e = {
        //     pageType: parseInt($("#pageType").val()),
        //     taskId: taskId
        // };
        // $.ajax({
        //     url: homeUrl + "/task/loadConfigUrls",
        //     data: e,
        //     async: !0,
        //     success: function(e) {
        //         1 == e.rs ? e.data && (m = r(e.data)) && m.length > 0 && (m.push("注意，这里是测试用，自动给出的可能只是部分相关网址。"),
        //             i(),
        //         $("#pageUrl").val() || ($("#pageUrl").val(m[0]),
        //             loadUrl())) : showMsgErr(e.msg)
        //     }
        // })
    }

    function a() {
        // var e = {
        //     pageType: parseInt($("#pageType").val()),
        //     taskId: taskId
        // };
        // $.ajax({
        //     url: homeUrl + "/task/xsite/loadConfigUrls",
        //     data: e,
        //     async: !0,
        //     success: function(e) {
        //         1 == e.rs ? e.data && (m = r(e.data)) && m.length > 0 && (m.push("注意，这里是测试用，自动给出的是最后采集到的数据的网址。"),
        //             i(),
        //         $("#pageUrl").val() || $("#pageUrl").val(m[0])) : showMsgErr(e.msg)
        //     }
        // })
    }

    function o(e, t) {
        return $.inArray(t, e) >= 0
    }

    function r(e) {
        var t = [];
        if (!e || 0 == e.length)
            return t;
        for (var i = 0, n = 0, a = e.length; n < a; n++) {
            var r = e[n]
                , l = {};
            (l = jsonClone(v)).urlType = r.urlType,
                l.url = r.url,
                l.valueType = r.valueType,
                l.listValues = r.listValues,
                l.start = r.start,
                l.end = r.end,
                l.step = r.step;
            var c = s(l);
            if (c && c.length > 0)
                for (var u = 0, d = c.length; u < d && !(i > 20); u++) {
                    var h = c[u];
                    o(t, h) || (t.push(h),
                        i++)
                }
        }
        return t
    }

    function s(e) {
        var t = [];
        return 1 == e.valueType ? t = c(e) : 2 == e.valueType ? t = l(e) : t.push(e.url),
            t
    }

    function l(e) {
        var t = [];
        if (!e.url)
            return t;
        if (e.url.indexOf("#ts_pageNo#") > 0) {
            if (!e.listValues)
                return t;
            var i = e.listValues.split(",");
            for (val in i) {
                var n = e.url.replace(/#ts_pageNo#/g, i[val]);
                t.push(n),
                    0
            }
        } else
            t.push(e.url),
                0;
        return t
    }

    function c(e) {
        var t = [];
        if (!e.url)
            return t;
        if (e.url.indexOf("#ts_pageNo#") > 0) {
            if (e.start >= 0 && e.end >= 0)
                for (var i = e.step, n = e.start, a = e.end, o = n; o <= a;) {
                    var r = e.url.replace(/#ts_pageNo#/g, o);
                    t.push(r),
                        0,
                        o += i
                }
        } else
            t.push(e.url),
                0;
        return t
    }

    function u(e) {
        if (!currFieldConfig || !currFieldConfig.name)
            return bootbox.alert("请先选择或定义字段！"),
                !1;
        $("#modal-data-deal").modal("show"),
        e && ($("li", $("#myConfigTab")).removeClass("layui-this"),
            $(".ts-" + e).addClass("layui-this"),
            $(".tab-pane", $("#tabbableConfig")).removeClass("layui-show"),
            $("#" + e).addClass("layui-show")),
            h()
    }

    function d(e) {
        y && y[0] ? insertAtCursor(y[0], e) : bootbox.alert("请先把光标放入输入框中要插入的位置（“字段前面添加”或“字段后面添加”）！")
    }

    function insertAtCursor(e, t) {
        if (document.selection)
            e.focus(),
                sel = document.selection.createRange(),
                sel.text = t,
                sel.select();
        else if (e.selectionStart || "0" == e.selectionStart) {
            var i = e.selectionStart
                , n = e.selectionEnd
                , a = e.scrollTop;
            e.value = e.value.substring(0, i) + t + e.value.substring(n, e.value.length),
            a > 0 && (e.scrollTop = a),
                e.focus(),
                e.selectionStart = i + t.length,
                e.selectionEnd = i + t.length
        } else
            e.value += t,
                e.focus()
    }

    function h() {
        initDataDealValue(),
            initDefaultValue(),
            initFileDown(),
            initReplaces(),
            initDataDeals(),
            initRegex(),
            initSelector(),
            initHtmlTags(currFieldConfig.htmlEles)
    }

    function f(e) {
        var t = $("#pageUrl").val();
        if (!t)
            return showMsgErr("典型网址不能为空"),
                !1;
        saveModalDataAllLocal(),
            saveAll(!1, !1);
        // var i = {
        //     url: t,
        //     taskId: taskId,
        //     fileSaveType: 2
        // };
        // $.ajax({
        //     url: homeUrl + "/publish/bookmark-crawl",
        //     type: "post",
        //     data: i,
        //     async: !0,
        //     traditional: !0,
        //     dataType: "json",
        //     success: function(e) {
        //         if (1 == e.rs) {
        //             var t = e.data;
        //             if (t) {
        //                 var i = homeUrl + "/data/list/" + taskId + "?openDataId=" + t;
        //                 window.open(i)
        //             } else
        //                 showMsgErr("采集数据为空")
        //         } else
        //             showMsgErr(e.msg)
        //     },
        //     error: function(e, t, i) {
        //         systemErr()
        //     }
        // })
    }

    function p() {
        var e = $("#pageUrl").val();
        if (!e)
            return showMsgErr("已有数据链接不能为空"),
                !1;
        saveModalDataAllLocal(),
            saveAll(!1, !1);
        // var t = {
        //     url: e,
        //     taskId: taskId,
        //     fileSaveType: 2
        // };
        // $.ajax({
        //     url: homeUrl + "/task/xsite/testDataDealNow",
        //     type: "post",
        //     data: t,
        //     async: !0,
        //     traditional: !0,
        //     dataType: "json",
        //     success: function(e) {
        //         if (1 == e.rs) {
        //             var t = e.data;
        //             if (t) {
        //                 var i = homeUrl + "/data/list/" + taskId + "?openDataId=" + t;
        //                 window.open(i)
        //             } else
        //                 showMsgErr("采集数据为空")
        //         } else
        //             showMsgErr(e.msg)
        //     },
        //     error: function(e, t, i) {
        //         systemErr()
        //     }
        // })
    }

    function g() {
        var e = $("#pageUrl").val();
        if (!e)
            return showMsgErr("已有数据链接不能为空"),
                !1;
        // var t = {
        //     url: e,
        //     taskId: taskId,
        //     fileSaveType: 2
        // };
        // $.ajax({
        //     url: homeUrl + "/task/xsite/showDataByUrl",
        //     type: "post",
        //     data: t,
        //     async: !0,
        //     traditional: !0,
        //     dataType: "json",
        //     success: function(e) {
        //         if (1 == e.rs) {
        //             var t = e.data;
        //             if (t) {
        //                 var i = homeUrl + "/data/list/" + taskId + "?openDataId=" + t;
        //                 window.open(i)
        //             } else
        //                 showMsgErr("该URL数据不存在或已删除")
        //         } else
        //             showMsgErr(e.msg)
        //     },
        //     error: function(e, t, i) {
        //         systemErr()
        //     }
        // })
    }

    isConfiger ? a() : n(),
        initStart(),
    isConfiger && h(),
        hideHtmlConfig(),
        $(".ts-save-all").on("click", function () {
            isConfiger && saveModalDataAllLocal(),
                saveAll()
        }),
        $(".ts-save-all-colse").on("click", function () {
            isConfiger && saveModalDataAllLocal(),
                saveAll(!0)
        }),
        $(".ts-save-all-modal").on("click", function () {
            saveModalDataAllLocal(),
                saveAll()
        }),
        $("#cssQueryTestBtn").on("click", function () {
            cssQueryTest()
        }),
        $("#ts-load-url").on("click", function () {
            loadUrl()
        }),
        $(".ts-show-render-config").on("click", function () {
            showRenderConfig()
        }),
        $("#ts-load-url-lazy").on("click", function () {
            loadUrlWithLazy()
        }),
        $(".ts-open-url").on("click", function () {
            var e = $("#pageUrl").val();
            if (!e)
                return showMsgErr("典型网址不能为空"),
                    !1;
            window.open(e)
        }),
        $("#pageUrl").keyup(function (e) {
            13 == e.keyCode && loadUrl()
        }),
        $(".ts-show-all-data").on("click", function () {
            showAllData()
        }),
        $("#ts-addRow").on("click", function () {
            checkPageType() && addNewRow()
        }),
        $(".ts-addRow").on("click", function () {
            checkPageType() && addNewRow()
        }),
        $("#ts-copyRow").on("click", function () {
            checkPageType() && copyRow()
        }),
        $("a[name=ts-delRow]").on("click", function () {
            var e = this
                , t = getRowFieldId($(e).closest("tr")[0])
                , i = allFieldConfigs[t];
            bootbox.confirm("确定要删除字段：" + i.name, function (t) {
                t && removeRow(e)
            })
        }),
        $("#ts-delAllRows").on("click", function () {
            delAllRows()
        }),
        $(".input-field").on("focus change keyup keydown", $("#" + fieldsTableId), function () {
            isConfiger || !$(this).attr("readonly") ? (isConfiger && saveModalDataAllLocal(),
                dealField(this),
                h()) : showMsgErr("该字段值在页面不可见，暂不支持修改，如有需求，可定义新的字段。")
        }),
        $(".input-field").on("blur", function () {
            dealFieldBlur(this)
        }),
        $("#dela-keeptxt").on("change", function () {
            var e = $(this).prop("checked");
        })
    $(".ts-open-extrator-detail").on("click", function () {
        t(2)
    }),
        $(".ts-open-extrator-list").on("click", function () {
            t(1)
        }),
        $(".ts-add-field-one").on("click", function () {
            e($(this))
        }),
        $(".ts-add-field-all").on("click", function () {
            $("a.ts-add-field-one").each(function (t, i) {
                e($(this))
            })
        }),
        $("input[type='checkbox']", $("#config-table,#commonConfig,#filterConfig")).on("click", function () {
            dealCheckConfig(this);
            var e = $(this).prop("checked");
            "useHtml" == $(this).attr("name") ? useHtmlAction(e) : "useLink" == $(this).attr("name") ? (useHtmlAction(e),
                useLinkAction(this)) : "mutiValue" == $(this).attr("name") ? mutiValueAction(this) : "useImg" == $(this).attr("name") ? useImgAction(this) : "required" == $(this).attr("name") ? requiredAction(this) : "delaTxt" == $(this).attr("name") || "dela" == $(this).attr("name") || ("mutiPage" == $(this).attr("name") ? mutiPageAction(this) : "dela-keeptxt" == $(this).attr("name") && delaKeepTxt(this)),
                showFieldFinalData()
        }),
        $("input[type='checkbox']", $("#config-table,#commonConfig,#filterConfig")).on("change", function () {
            dealCheckConfig(this);
            var e = $(this).prop("checked");
            "useHtml" == $(this).attr("name") ? useHtmlAction(e) : "useLink" == $(this).attr("name") ? (useHtmlAction(e),
                useLinkAction(this)) : "mutiValue" == $(this).attr("name") ? mutiValueAction(this) : "useImg" == $(this).attr("name") ? useImgAction(this) : "required" == $(this).attr("name") ? requiredAction(this) : "delaTxt" == $(this).attr("name") || "dela" == $(this).attr("name") || ("mutiPage" == $(this).attr("name") ? mutiPageAction(this) : "dela-keeptxt" == $(this).attr("name") && delaKeepTxt(this)),
                showFieldFinalData()
        }),
        $("input[type='checkbox']", $("#htmlTagSelectOpt")).on("click", function () {
            dealCheckConfig(this),
            "useHtml" == $(this).attr("name") && useHtmlAction($(this).prop("checked")),
                showFieldFinalData()
        }),
        $("#mutiPager-switch").on("click", function () {
            switchMutiPagerAll($(this).prop("checked"))
        });
    var m = [];
    // $.ui.autocomplete.prototype._renderItem = function(e, t) {
    //     var i = this.term.split(" ").join("|")
    //         , n = new RegExp("(" + i + ")","gi")
    //         , a = t.label.replace(n, "<strong>$1</strong>");
    //     return $("<li></li>").data("item.autocomplete", t).append("<a>" + a + "</a>").appendTo(e)
    // }
    ;
    var v = {
        id: "",
        urlType: 2,
        url: "",
        paraName: "#ts_pageNo#",
        valueType: 1,
        listValues: "",
        start: 1,
        end: 1,
        step: 1,
        addZero: !1,
        orderBy: "asc"
    };
    $("#conf-xpath").on("click", function () {
        u("confXpath")
    }),
        $("a[name='conf-xpath'").on("click", function () {
            u("confXpath")
        }),
        $(".ts-data-deal-more").on("click", function () {
            u()
        }),
        $("a[name=conf-data-deal-more]").on("click", function () {
            $tr = $(this).closest("tr")[0],
                switchFieldByTr($tr),
                u()
        }),
        $(".input-field").on("dblclick", function () {
            if (!isConfiger) {
                if ($(this).attr("readonly"))
                    return void bootbox.alert("该字段值在页面不可见，但服务器可以处理。");
                u()
            }
        }),
        $(".ts-save-field-all-temp").on("click", function () {
            saveModalDataAllLocal(),
                showMsgSuc(localSaveMsg)
        }),
        $(".ts-crawl-url-now").on("click", function () {
            f()
        }),
        $(".ts-crawl-url-now-modal").on("click", function () {
            f()
        }),
        $(".ts-test-dataDeal-now").on("click", function () {
            p()
        }),
        $(".ts-showDataByUrl").on("click", function () {
            g()
        }),
        $(".ts-conf-input-field").on("blur", function () {
            saveModalDataAllLocal()
        }),
        $("#xpathValue").on("blur", function () {
            switchMutiPager(0)
            saveXpathAndLocation()
        }),
        $("#xpathValue").on("focus", function () {
            switchMutiPager(0)
            saveXpathAndLocation()
        }),
        $("#modal-data-deal").on("hide.bs.modal", function () {
            saveModalDataAllLocal()
        }),
        $(".ts-pager-xpathValue").on("blur", function () {
            switchMutiPager(!0)
            var e = $("#pageSelector").val();
            savaSelectorPage(e, extractElementsCh(e));
            clearIframe();
            locationIfrSelector(currFieldConfig.pageSelector)
            genAndShowPageExtractValue(e)
        }),
        $(".ts-pager-xpathValue").on("focus", function () {
            switchMutiPagerAll(!0)
        }),
        $(".ts-show-mutiPager-more").on("click", function () {
            $("#taskConfig-mutiPage-modal").modal("show"),
                initMutiPagrValue()
        }),
        $("#taskConfig-mutiPage-modal").on("hide.bs.modal", function () {
            saveMutiPagrValue()
        }),
        $(".ts-fill-huanghang").on("click", function () {
            $("#pageConcat").val("<br/>")
        });
    var C;
    $("input[name=from]", $("#replace-table>tbody tr")).on("focus", function () {
        C = $(this)
    }),
        $(".ts-fill-regex-fuzzy").on("click", function () {
            C && C[0] ? insertAtCursor(C[0], ".*") : bootbox.alert('请先把光标放入输入框中要插入的位置（表格"将字符串"该列）！')
        });
    var y;
    $("textarea", $("#commonDataDeal-form")).on("focus", function () {
        y = $(this)
    }),
        $(".ts-fill-paraField-append").on("click", function () {
            var e = $(this).attr("fieldPara");
            e && d("#[" + e + "]#")
        }),
        $(".ts-fill-paraField-link-append").on("click", function () {
            d('<a href="#[tj_url]#" target="_blank">#[title]#</a>')
        }),
        $("#ajaxPage").on("change", function () {
            loadUrl()
        }),
        $("#save-xpath").on("click", function () {
            saveXpathAndLocation()
        }),
        $("#test-xpath").on("click", function () {
            testXpath()
        }),
        $(".ts-xpath-test-location").on("click", function () {
            testXpathAndLocation()
        }),
        $(".ts-xpath-select-parent").on("click", function () {
            var e = $("#xpathValue").val();
            if (e) {
                var t = e.split("/");
                if (t && t.length > 2) {
                    var i = t.length
                        , n = t;
                    e.endsWith(myEle) || e.endsWith(myEle + "[1]") || e.endsWith(myEle + "[2]") || e.endsWith(myEle + "[3]") ? i > 3 && (n = t.slice(0, i - 2)) : n = t.slice(0, i - 1);
                    var a = n.join("/");
                    $("#xpathValue").val(a),
                        saveXpathAndLocation()
                } else
                    bootbox.alert("无法再扩大选取区域")
            } else
                bootbox.alert("未选择区域，请先在页面中点选一个小的区域")
        }),
        $(".ts-page-xpath-select-parent").on("click", function () {
            var e = $("#pageSelector").val();
            if (e) {
                var t = e.split("/");
                if (t && t.length > 2) {
                    var i = t.length
                        , n = t;
                    e.endsWith(myEle) || e.endsWith(myEle + "[1]") || e.endsWith(myEle + "[2]") || e.endsWith(myEle + "[3]") ? i > 3 && (n = t.slice(0, i - 2)) : n = t.slice(0, i - 1);
                    var a = n.join("/");
                    $("#pageSelector").val(a),
                        switchMutiPagerAll(1)
                } else
                    bootbox.alert("无法再扩大选取区域")
            } else
                bootbox.alert("未选择区域，请先在页面中点选一个小的区域")
        }),
        $(".ts-save-xpath").on("click", function () {
            saveXpathAndLocation()
        }),
        $("#conf-default").on("click", function () {
            u("commonConfig")
        }),
        $("a[name=conf-default]").on("click", function () {
            u("commonConfig")
        }),
        $("#save-defaultValue").on("click", function () {
            saveDefaultValue()
        }),
        $("#conf-regex").on("click", function () {
            u("sysRegular")
        }),
        $("a[name=conf-regex]").on("click", function () {
            u("sysRegular")
        }),
        $("a[name=conf-repalces]").on("click", function () {
            u("replaces")
        }),
        $(".ts-save-regex").on("click", function () {
            saveRegexAndShow()
        }),
        $("#test-regex").on("click", function () {
            testRegex(!0)
        }),
        $("#test-regex-matchGp").on("click", function () {
            testRegexMatchGp(!0)
        }),
        $("#ts-match-regex").on("blur", function () {
            $("#ts-match-regex").val() || $("#ts-regex-result").html("")
        }),
        $("#conf-href").on("click", function () {
            modifyHref()
        }),
        $("#conf-clear-row").on("click", function () {
            cleanRowAction(this)
        }),
        $(".ts-clear-page-select").on("click", function () {
            resetPageSelect()
        }),
        $("#groupSelect").on("click", function () {
            dealGroupSelect(this)
        }),
        $("#pageType").on("change", function () {
            setPageType($(this).val())
        }),
        $("button[name=selectConfigBtn]").on("click", function () {
            selectConfig(this)
        }),
        $("a[name=conf-clean-html]").on("click", function () {
            cleanHtmlAction(this)
        }),
        $("a[name='conf-clean-row']").on("click", function () {
            cleanRowAction()
        }),
        $("span[data-regex]").on("click", function () {
            setDefRegex(this)
        }),
        $("span[data-regex-group]").on("click", function () {
            setDefRegexGroup(this)
        }),
        $(".ts-fullscreen").on("click", function () {
            launchFullscreen(document.documentElement)
        }),
        $(".ts-fullscreen-exit").on("click", function () {
            exitFullscreen()
        }),
        $("a[name=ts-replace-addRow]").on("click", function () {
            addRowReplace()
        }),
        $("a[name=ts-replace-delRow]").on("click", function () {
            removeRowReplace(this)
        }),
        $("a[name=ts-adv-addRow]").on("click", function () {
            addRowAdv($(this).data("trid"))
        }),
        $("a[name=ts-adv-delRow]").on("click", function () {
            removeRowAdv(this)
        }),
        $(".ts-taskFtpTab").on("click", function () {
            var e = homeUrl + "/task/ftp/" + taskId;
            window.open(e)
        }),
        $("#pageType").trigger("change");
});

var pageType = $('#pageType').val();
var win = "Window", myEle = "tj";
var dataDealTableId = "adv-deal-table", advSortNo = 0;
var extractorTip = '<div id="ts-select-tips" class="ts-select-tips">提示: 当前字段为：<span id="tip-field-name"></span><br>1.点击可选中数据，再次点击相同数据则取消<br>2.先在左侧选择字段，再点选对应数据<br>3.点击”重置当前字段配置”，可清空所有点选</div>';
var $currTr, currFieldConfig, storageType = 1, fileConfigId, mutiPagerSwitch = !1, extractorEdited = !1,
    descriptionSelector = '//meta[@name="description"]', keywordsSelector = '//meta[@name="keywords"]', idOrder = 0,
    iconSuc = "ace-icon fa fa-check green bigger-110", iconMeta = "green ace-icon fa fa-info-circle",
    iconWarn = "ace-icon fa fa-info-circle orange", allFieldConfigs = {}, fieldConfigObj = {
        id: "",
        name: "",
        required: !1,
        useHtml: !1,
        useOuterHtml: !1,
        useLink: !1,
        mutiValue: !1,
        pageMutiValue: !1,
        isMeta: !1,
        selectors: "",
        fieldValues: [],
        defaultValue: "",
        valueType: "text",
        attrName: "",
        matchRegex: "",
        matchReplace: "",
        matchGp: "",
        matchSplit: "",
        replaces: [],
        dataDealVos: [],
        cleanHtml: !1,
        keepAlt: 0,
        htmlEles: "",
        groupSelect: !0,
        fileSaveType: 0,
        fileTypes: "1",
        fileUrlPattern: "",
        concatDelimiter: "",
        useImg: !1,
        imgAttr: "",
        delaTxt: 0,
        dela: 0,
        delAs: "",
        delAllImg: 0,
        delImg: "",
        delBlank: 0,
        pType: 0,
        preTxt: "",
        tailTxt: "",
        randType: 0,
        minRd: 0,
        maxRd: 0,
        minRdtStr: "",
        maxRdtStr: "",
        timeFmt: "",
        txtRd: "",
        mutiPage: 0,
        pageMode: 1,
        pageSelector: "",
        pageSave: 1,
        pageConcat: "",
        maxPage: 0,
        maxCrawl: 0,
        urlContain: "",
        lenType: 0,
        lenLimit: 0,
        filterType: 1,
        noInclude: "",
        mustInclude: "",
        renameFile: !0
    }, replaceDto = {
        from: "",
        to: "",
        sortNo: 0
    }, fileDownConfig = {
        httpPrefix: "",
        fileTypes: "",
        fileUrlPattern: "",
        renameFile: !0
    };

var trHlClass = "hl-tr"
    , fieldsTableId = "fields-table";

var isConfiger = false;//是否只是配置器，不包含selector


function changeValueType() {
    var e = parseInt(getCheckRadio("randType"));
    currFieldConfig.valueType = e > 0 ? "random" : $("#valueType").val()
}

function removeRowAdv(e) {
    $tr = $(e).closest("tr")[0],
        $tr.remove()
}

function removeRowReplace(e) {
    if ($tr = $(e).closest("tr")[0],
    2 == getReplaceTrCount())
        return resetTemplateReplace($($tr)),
            void showMsgErr("最后一行不能删除，已为您清空值");
    $tr.remove()
}

function getReplaceTrCount() {
    return $("#replace-table>tbody tr").size()
}

function addNewRowIfr() {
    checkPageType() && addNewRow()
}

function resetPageSelect() {
    layer.confirm("确定要重置已点选的内容吗？（只影响当前字段：" + getCurrFieldName() + "）", function (e) {
        e && clearAndReset()
    })
}

function showAllData() {
    $("#modal-table-data").modal("show"),
        removeDataTableTrs(),
        genAllData()
}

function showRenderConfig() {
    $("#modal-render-config").modal("show")
}

function genAllData() {
    var e = "";
    for (var t in allFieldConfigs)
        e += genDataTableTr(allFieldConfigs[t]);
    e && $("#all-data-table tbody").append(e)
}

function genDataTableTr(e) {
    for (var t = "<tr><td>" + e.name + "</td>", i = genExtractValueArr(e, extractElementsCh(e.selectors), e.useHtml, e.useLink), n = "", a = 0, o = i.length; a < o; a++)
        i[a] && i[a].trim() && (n += processData(i[a], e),
        a < o - 1 && (n += "<br>"));
    return t = t + "<td>" + n + "</td></tr>"
}

function removeDataTableTrs() {
    var e = $("#all-data-table>tbody tr");
    e[0] && e.empty()
}

function initMutiPagrValue() {
    if (!currFieldConfig)
        return !1;
    dealCheckBox("mutiPage", currFieldConfig.mutiPage),
        showMutiPage(1 == currFieldConfig.mutiPage),
        $("#pageSelector").val(currFieldConfig.pageSelector),
        checkRadio("pageSave", currFieldConfig.pageSave),
        $("#pageConcat").val(currFieldConfig.pageConcat),
        $("#maxPage").val(currFieldConfig.maxPage),
        $("#urlContain").val(currFieldConfig.urlContain)
}

function saveMutiPagrValue() {
    currFieldConfig.pageSelector = $("#pageSelector").val(),
        currFieldConfig.pageSave = getCheckRadio("pageSave"),
        currFieldConfig.pageConcat = $("#pageConcat").val(),
        currFieldConfig.maxPage = $("#maxPage").val(),
        currFieldConfig.urlContain = $("#urlContain").val()
}

function switchMutiPagerAll(e) {
    if (e) {
        switchMutiPager(!0),
            clearIframe();
        var t = $("#pageSelector").val();
        locationIfrSelector(t),
            genAndShowPageExtractValue(t)
    } else
        switchMutiPager(!1),
            initTrShow($currTr)
}

function cleanHtmlAction(e) {
    currFieldConfig.cleanHtml = !currFieldConfig.cleanHtml,
        dealCheckBox("cleanHtml", currFieldConfig.cleanHtml),
        saveCurrFieldConfig(),
        initCleanHtmlShow(e)
}

function initCleanHtmlShow(e) {
    currFieldConfig.cleanHtml ? $("i", $(e)).removeClass("hide") : $("i", $(e)).addClass("hide")
}

function genAndShowPageExtractValue(e) {
    showPageFieldValue(genExtractValueArrForPage(extractElementsCh(e)))
}

function genExtractValueArrForPage(e) {
    if (!e || 0 == e.length)
        return [];
    for (var t = [], i = 0, n = e.length; i < n; i++) {
        var a = "";
        isInArray(t, a = genLinkHrefShowValue(e[i])) ? a = "" : t.push(a)
    }
    return t
}

function switchMutiPager(e) {
    e ? (mutiPagerSwitch = !0,
        $(".ts-pager-xpathValue").removeAttr("readonly")) : (mutiPagerSwitch = !1,
        $(".ts-pager-xpathValue").attr("readonly", !0)),
        dealCheckBox("mutiPager-switch", e)
}

function mutiPageAction(e) {
    $(e).prop("checked") ? (currFieldConfig.mutiPage = 1,
        showMutiPage(!0)) : (currFieldConfig.mutiPage = 0,
        showMutiPage(!1)),
        saveCurrFieldConfig()
}

function saveAll(e, t) {
    if (genFieldArray().length <= 0)
        return layer.alert("未定义字段，至少需要一个字段！"),
            !1;
    saveCurrFieldConfig();
    var o = {
        fieldArr: JSON.stringify(genFieldArray()),
        pageType: parseInt($("#pageType").val()),
        taskId: taskId,
        url: $("#pageUrl").val()
    };
    console.log(o);
    return void 0 === t && (t = !0),
        // $.ajax({
        //     url: getSaveExtratorUrl(),
        //     type: "post",
        //     data: o,
        //     async: t,
        //     traditional: !0,
        //     dataType: "json",
        //     success: function(t) {
        //         1 == t.rs ? (showSaveSuc(),
        //         e && window.close()) : bootbox.alert(t.msg)
        //     },
        //     error: function(e, t, i) {
        //         systemErr()
        //     }
        // }),
        !0
}

function delaKeepTxt(e) {
    var t = $(e).prop("checked");
    currFieldConfig.dela = t ? 2 : 0,
        saveCurrFieldConfig()
}

function requiredAction(e) {
    var t = $(e).prop("checked");
    currFieldConfig.required = t ? 2 : 0;
    var i = genFinalDatas(currFieldConfig.selectors,currFieldConfig);
    saveCurrFieldConfig(),
        setFieldFinalData(i.join("\n")),
        showFieldValue(i)
}

function removeRow(e) {
    $tr = $(e).closest("tr")[0];
    var t = getRowFieldId($tr);
    delete allFieldConfigs[t],
        removeFieldValues(),
        setToPreOrNextTr($tr),
        $tr.remove()
}

function setToPreOrNextTr(e) {
    var t = $(e).prev();
    if (t[0] && !t.attr("id"))
        $currTr = t,
            currFieldConfig = getExistFieldConfig(t),
            initTrShow(t);
    else {
        var i = $(e).next();
        i[0] && !i.attr("id") ? ($currTr = i,
            currFieldConfig = getExistFieldConfig(i),
            initTrShow(i)) : ($currTr = "",
            currFieldConfig = {},
            setEmptyConfig(),
            clearIframe())
    }
}

function delAllRows() {
    layer.confirm("确定要删除全部字段吗?", function (e) {
        e && ($("#" + fieldsTableId + ">tbody tr:not(:first)").each(function () {
            $(this).remove()
        }),
            allFieldConfigs = {},
            $currTr = "",
            currFieldConfig = null,
            setTitle(""),
            removeFieldValues(),
            setEmptyConfig(),
            clearIframe())
    })
}

function setEmptyConfig(e) {
    initFieldConfigShow(JSON.parse(JSON.stringify(fieldConfigObj)))
}

function addFieldsblur() {
    if ($("#add-fields").attr("aria-expanded") == "true") {
        $("#add-fields").parent().removeClass("open");
        $("#add-fields").attr("aria-expanded", "false")
    }
}

function saveModalDataAllLocal() {
    saveDataDealValue(),
        saveDefaultValue(),
        saveFileDown(),
        saveFileStorage(),
        saveReplaces(),
        saveDataDealAdv(),
        saveRegex(),
        saveXpath(),
        saveMutiPagrValue(),
        saveCurrFieldConfig(),
        resetFieldIconCurr(),
        initCurrTrShow()
}

function saveReplaces() {
    currFieldConfig.replaces = genReplaceArray()
}

function saveDataDealAdv() {
    currFieldConfig.dataDealVos = genDataDealArray()
}

function genReplaceArray() {
    var e = [];
    return $("#replace-table>tbody tr:not(:first)").each(function (t) {
        var i = $(this)
            , n = $("input[name=from]", i).val()
            , a = $("input[name=to]", i).val()
            , o = $("input[type='checkbox'][name=reg]", i).prop("checked") ? 1 : 0
            , r = {};
        r.from = n,
            r.to = a || "",
            r.reg = o,
            r.sortNo = t + 1,
        n && e.push(r)
    }),
        e
}

function genDataDealArray() {
    var e = [];
    return $("#adv-deal-table>tbody tr:gt(0)").each(function (t) {
        var i = $(this)
            , n = i.data("type")
            , a = {};
        if (a.typeStr = n,
        "delTag" == n) {
            var o = $("select[name=tagName]", i).val()
                , r = $("select[name=posType]", i).val()
                , s = $("input[name=delCount]", i).val();
            if (!o)
                return !0;
            var l = $("input[type='checkbox'][name=leftText]", i).prop("checked") ? 1 : 0;
            a.tagName = o,
                a.posType = r,
                a.delCount = s,
                a.leftText = l
        }
        var c = $("input[name=sortNo]", i).val();
        c || (c = 0),
            a.sortNo = c,
            e.push(a)
    }),
        e
}

function saveMutiPagrValue() {
    currFieldConfig.pageSelector = $("#pageSelector").val(),
        currFieldConfig.pageSave = getCheckRadio("pageSave"),
        currFieldConfig.pageConcat = $("#pageConcat").val(),
        currFieldConfig.maxPage = $("#maxPage").val(),
        currFieldConfig.urlContain = $("#urlContain").val()
}

function saveXpath() {
    var e = $("#xpathValue").val();
    if (e == "") {
        setAndChangeCheckBox("mutiValue", 0);
        setAndChangeCheckBox("groupSelect", 0);
    }
    currFieldConfig.selectors,
        currFieldConfig.selectors = e,
        saveCurrFieldConfig()
}

function saveXpathAndLocation() {
    saveXpath(),
        initCurrTrShow()
}

function saveFileDown() {
    var e = getCheckRadio("fileSaveType");
    currFieldConfig.fileSaveType = e,
        saveCurrFieldConfig()
}

function initFileDown() {
    checkRadio("fileSaveType", currFieldConfig.fileSaveType),
        checkRadio("storageType", storageType),
        $("#httpPrefix").val(fileDownConfig.httpPrefix)
}

function saveFileStorage() {
    storageType = getCheckRadio("storageType"),
        fileDownConfig.httpPrefix = $("#httpPrefix").val(),
        saveCurrFieldConfig()
}

function saveDefaultValue() {
    currFieldConfig.defaultValue = $("#ts-defaultValue").val(),
        currFieldConfig.concatDelimiter = $("#concatDelimiter").val(),
        currFieldConfig.imgAttr = $("#imgAttr").val(),
        currFieldConfig.valueType = $("#valueType").val(),
        currFieldConfig.attrName = $("#attrName").val(),
        saveCurrFieldConfig(),
        $("#default-value-modal").modal("hide")
}

function saveDataDealValue() {
    currFieldConfig.delAllImg = getCheckRadio("delAllImg");
    var e = getCheckBox("delImgItem");
    currFieldConfig.delImg = e.join(","),
        currFieldConfig.dela = getCheckRadio("dela");
    var t = getCheckBox("delAsItem");
    currFieldConfig.delAs = t.join(",");
    var i = isCheckedById("pType") ? 1 : 0;
    currFieldConfig.pType = i;
    var n = isCheckedById("keepAlt") ? 1 : 0;
    currFieldConfig.keepAlt = n,
        currFieldConfig.preTxt = $("#preTxt").val(),
        currFieldConfig.tailTxt = $("#tailTxt").val(),
        currFieldConfig.randType = getCheckRadio("randType"),
        currFieldConfig.minRd = $("#minRd").val(),
        currFieldConfig.maxRd = $("#maxRd").val(),
        currFieldConfig.minRdtStr = $("#minRdtStr").val(),
        currFieldConfig.maxRdtStr = $("#maxRdtStr").val(),
        currFieldConfig.timeFmt = $("#timeFmt").val(),
        currFieldConfig.txtRd = $("#txtRd").val(),
        currFieldConfig.lenType = $("#lenType").val(),
        currFieldConfig.lenLimit = $("#lenLimit").val(),
        currFieldConfig.filterType = getCheckRadio("filterType"),
        currFieldConfig.noInclude = $("#noInclude").val(),
        currFieldConfig.mustInclude = $("#mustInclude").val()
}

function isCheckedById(e) {
    return $("#" + e).prop("checked")
}

function dealField(e) {
    $tr = $(e).closest("tr")[0],
        switchFieldByTr($tr),
        hideHtmlConfig()
}

function switchFieldByTr(e) {
    $currTr = e,
        currFieldConfig = getCurrFieldConfig(),
        hlCurrTr(e),
        initTrShow(e),
        switchMutiPager(!1)
}

function switchMutiPager(e) {
    e ? (mutiPagerSwitch = !0,
        $(".ts-pager-xpathValue").removeAttr("readonly")) : (mutiPagerSwitch = !1,
        $(".ts-pager-xpathValue").attr("readonly", !0)),
        dealCheckBox("mutiPager-switch", e)
}

function initTrShow(e) {
    var t = getRowFieldId(e);
    initFieldConfigShow(allFieldConfigs[t]),
        resetValueAndPageSelector(),
        resetFieldIcon(e)
}

function resetValueAndPageSelector() {
    showFieldValue(extractAndProcess(extractElementsCh(currFieldConfig.selectors), currFieldConfig)),
        showFieldFinalData(),
        clearIframe(),
        locationIfrSelector(currFieldConfig.selectors)
}

function extractAndProcess(e, t) {
    for (var i = genExtractValueArr(t, e, t.useHtml, t.useLink, t.valueType, t.attrName, t), n = [], a = 0, o = i.length; a < o; a++)
        n.push(processData(i[a], t));
    return n
}

function extractAndProcessOri(e, t) {
    for (var i = genExtractValueArrOri(t, e, t.useHtml, t.useLink, t.valueType, t.attrName, t), n = [], a = 0, o = i.length; a < o; a++)
        n.push(processData(i[a], t));
    return n
}

function genExtractValueArr(fldConfig, e, t, i, n, a) {
    var o = genExtractValueArrOri(fldConfig, e, t, i, n, a);
    return i && (o = genLinkForUseLink(o)),
        o
}

function useHtmlAction(e) {
    if (currFieldConfig.selectors) {
        var t = "text";
        e && (t = "html"),
            changeCurrValueType(t, "");
        if (!e) {
            currFieldConfig.useHtml = 0;
            dealCheckBox()
        }
        var i = genSelectorValueArrOri(currFieldConfig, currFieldConfig.selectors, currFieldConfig.useHtml, currFieldConfig.useLink, currFieldConfig.valueType, currFieldConfig.attrName);
        saveCurrFieldConfig(),
            setFieldFinalData(i.join("\n")),
        currFieldConfig.useLink && (i = genLinkForUseLink(i)),
            showFieldValue(i)
    }
}

function genSelectorValueArrOri(fldConfig, e, t, i, n, a) {
    if (!e)
        return [];
    var o = extractElementsCh(e);
    return o && 0 != o.length ? genExtractValueArrOri(fldConfig, o, t, i, n, a) : []
}

function genLinkForUseLink(e) {
    var t = [];
    if (!e || 0 == e.length)
        return t;
    for (var i = 0, n = e.length; i < n; i++) {
        var a = genLinkHrefShowValueByValue(e[i]);
        t.push(a)
    }
    return t
}

function genLinkHrefShowValue(e) {
    return genLinkHrefShowValueByValue(genLinkHrefValue(e))
}

function genLinkHrefValue(e) {
    if (!e || !$(e).is("a") && e.nodeName.toLowerCase() != get())
        return "";
    var t = e;
    e.nodeName.toLowerCase() == get() && (t = e.parentNode);
    var i = $(t).attr("href");
    return i || (i = $(t).attr("tshref")) ? "#" == i || i.toLowerCase().startsWith("javascript") ? "" : i : ""
}

function genLinkHrefShowValueByValue(e) {
    return e ? (e.startsWith("/") && (e = getTargetSiteHomeUrl() + e),
    '<a href="' + e + '" target="_blank">' + e + "</a>") : ""
}

function handleInnerCode(l) {
    l = l.replaceAll("tshref", "href");
    l = l.replaceAll("_ts_Highlight_Select", "")
    return l;
}

function genExtractValueArrOri(fldConfig, e, t, i, n, a) {
    if (!e || 0 == e.length)
        return [];
    for (var o = [], r = 0, s = e.length; r < s; r++) {
        var l = ""
            , c = e[r];
        i ? isInArray(o, l = genLinkHrefValue(c)) && (l = "") : fldConfig.useImg ? l = genImgUrlShowValue(c, fldConfig) : (n ? "text" == n ? l = $(c).text() : "html" == n ? (c = deleteSdes(e[r]),
            l = html2Escape($(c).html())) : "ohtml" == n ? (c = deleteSdes(e[r]),
            l = html2Escape($(c).prop("outerHTML"))) : "ownText" == n ? l = $(c).ownText() : "attr" == n && a ? l = isLinkEle(c) && "href" == a ? genLinkHrefValue(c) : $(c).attr(a) : "random" == n && (l = "随机值，不可预览！") : l = $(c).text(),
        t && (c = deleteSdes(e[r]),
            l = html2Escape($(c).html())))
        if (fldConfig.required) {
            if (l != "" && l.trim() != "") {
                if ("random" != n) {
                    l = handleInnerCode(l)
                    o.push(l)
                } else {
                    l = "随机值，不可预览！"
                    o.push(l)
                }
            }
        } else {
            if ("random" != n) {
                l = handleInnerCode(l)
                o.push(l)
            } else {
                l = "随机值，不可预览！"
                o.push(l)
            }
        }
    }
    return o
}

function isLinkEle(e) {
    return !!e && (!!$(e).is("a") || !(e.nodeName.toLowerCase() != get() || (finalEle = e.parentNode,
        !$(finalEle).is("a"))))
}

function executeDelaKeepText(e) {
    $(e).find("a");
}

function genImgUrlShowValue(e, fldConfig) {
    if (!e && e.nodeName.toLowerCase() != get())
        return "";
    var t = e;
    if (e.nodeName.toLowerCase() == get() && (t = e.parentNode),
    "img" == t.nodeName.toLowerCase())
        return tryGetImgUrl(t, fldConfig);
    var i = $("img", t)
        , n = ",";
    fldConfig.concatDelimiter && (n = fldConfig.concatDelimiter);
    var a = "";
    if (i && i.length > 0) {
        for (var o = [], r = 0, s = i.length; r < s; r++) {
            var l = tryGetImgUrl(i[r], fldConfig);
            l && o.push(l)
        }
        a = o.join(n)
    }
    return a
}

function tryGetImgUrl(e, t) {
    var i = ""
        , n = $(e);
    return t.imgAttr ? (i = n.attr(t.imgAttr)) || showMsgErr("图片属性不存在值，请检查源码，或不填或使用src") : ((i = n.attr("data-src")) || (i = n.attr("data-url")),
    i || (i = n.attr("data-original")),
    i || (i = n.attr("#src")),
    i || (i = n.attr("src"))),
        i
}

function get() {
    return myEle
}

function deleteSdes(e) {
    var t = $(get(), $(e));
    if (t[0] && t.length > 0) {
        var i = $(e).clone()
            , n = $(get(), i);
        return $.each(n, function (e, t) {
            var i = $(t);
            i.is(get()) && i.contents().unwrap()
        }),
            i
    }
    return e
}

function processData(e, t) {
    var i = dealRegex(e, t.matchRegex, t.matchReplace);
    return i = dealReplace(i, t.replaces),
        i = dealRegexGroup(i, t.matchGp, t.matchSplit),
        i = dealPreTailAppend(i, t.preTxt, t.tailTxt, t.pType),
        t.defaultValue && !i ? t.defaultValue : i
}

function replaceAll(e, t, i) {
    try {
        e && t && (e = e.replace(new RegExp(t, "gm"), i))
    } catch (e) {
        showMsgErr("正则语法错误，注意模糊要使用点星.*，而不是*")
    }
    return e
}

function dealReplace(e, t) {
    if (!e || !t || 0 == t.length)
        return e;
    for (var i = e, n = 0, a = t.length; n < a; n++) {
        var o = t[n];
        i = replaceAll(i, o.from, o.to)
    }
    return i
}

function dealRegex(e, t, i) {
    if (!e || !t)
        return e;
    var n = new RegExp(t, "g");
    if (i)
        return e.replace(n, i);
    var a = e.match(n);
    return a ? a.join("") : ""
}

function dealRegexGroup(e, t, i) {
    if (!e || !t)
        return e;
    void 0 === i && (i = "");
    var n = new RegExp(t, "g").exec(e);
    if (e && e.length > 1) {
        for (var a = [], o = 1, r = e.length; o < r; o++)
            a.push(e[o]);
        return a.join(i)
    }
    return ""
}

function dealPreTailAppend(e, t, i, p) {
    if (t == '' && i == '')
        return e;
    if (p && e == '')
        return e;
    return (t?t:'') + e + (i?i:'');
}

function locationIfrSelector(e) {
    runIfrFun("locationSelector", e)
}

function showFieldFinalData() {
    setFieldFinalData(genFinalDatas(currFieldConfig.selectors, currFieldConfig))
}

function setFieldFinalData(e) {
    $(".ts-show-final-data").html(e)
}

function genFinalDatas(e, t) {
    return extractAndProcessOri(extractElementsCh(e), t)
}

function genFinalDatasString(e, t) {
    return genFinalDatas(e, t).join(",");
}

function removeFieldValues() {
    var e = $("#data-table>tbody tr");
    e[0] && e.empty()
}

function removePageFieldValues() {
    var e = $("#page-data-table>tbody tr");
    e[0] && e.empty()
}

function showFieldValue(e) {
    if (removeFieldValues(),
    e && !(e.length <= 0) && e && e.length > 0)
        for (var t = 0, i = e.length; t < i; t++)
            if (e[t] && e[t].trim()) {
                var n = genTrValue(e[t]);
                if (t >= 6 && (n = genTrValue('<a href="javascript:showAllData()"><font color="red">当前选中数据总数：' + i + "条,省略显示" + (i - t) + "条...</font></a>")),
                n && "<tr></tr>" != n && $("#data-table>tbody").append(n),
                t >= 6)
                    break
            }
    showToAllFieldsDataTable();
}

function showPageFieldValue(e) {
    if (removePageFieldValues(),
    e && !(e.length <= 0) && e && e.length > 0)
        for (var t = 0, i = e.length; t < i; t++)
            if (e[t] && e[t].trim()) {
                var n = genTrValue(e[t]);
                if (t >= 6 && (n = genTrValue('<font color="red">当前选中数据总数：' + i + "条,省略显示" + (i - t) + "条...</font>")),
                n && "<tr></tr>" != n && $("#page-data-table>tbody").append(n),
                t >= 6)
                    break
            }
}

function genTrValue(e) {
    return e ? "<tr><td class='layui-table-cell'>" + e + "</td></tr>" : ""
}

function extractElementsCh(e) {
    return runIfrFun("extractElements", e)
}

function hideHtmlConfig() {
    isConfiger && (currFieldConfig && currFieldConfig.useHtml ? $(".ts-show-for-html").css("display", "block") : $(".ts-show-for-html").css("display", "none"))
}

function dealCheckConfig(e) {
    if ($currTr) {
        var t = $(e).attr("name")
            , i = $(e).prop("checked");
        dealCheckBox(t, i),
            currFieldConfig[t] = i,
            "useHtml" == t ? (dealCheckBox("cleanHtml", i),
                switchHtmlTagdiv(i),
                currFieldConfig.cleanHtml = i) : "cleanHtml" == t && switchHtmlTagdiv(i),
            saveCurrFieldConfig()
    }
}

function dealFieldBlur(e) {
    $tr = e.parentNode.parentNode;
    var t = $(e).val();
    setTitle(t),
        currFieldConfig.name = t,
        saveCurrFieldConfig()
}

function checkPageType() {
    var e = genFieldArray().length;
    if (pageType == listType) {
        if (e >= 1)
            return layer.alert("列表页只能添加一个字段,如需多字段，请使用详情页配置"),
                !1
    } else if (pageType == detailType && e >= 30)
        return layer.alert("详情页只能添加30字段,如需更多字段，请反馈给我们！"),
            !1;
    return !0
}

function genFieldArray() {
    var e = [];
    for (var t in allFieldConfigs) {
        var i = allFieldConfigs[t];
        e.push(i)
    }
    return e
}

function copyRow() {
    if ($currTr) {
        var e = jsonClone(currFieldConfig)
            , t = addRow()
            , i = getRowFieldId(t);
        setFieldConfigObjCommon(t, e),
            allFieldConfigs[i] = e
    } else
        layer.alert("请选择要复制的字段，鼠标点一下字段名输入框即可")
}

function setFieldConfigObjCommon(e, t) {
    var i = getFieldName(e)
        , n = getRowFieldId(e);
    return t.id = n,
        t.name = i,
        t
}

function getRowFieldId(e) {
    return $("input[name='rowFieldId']", e).val()
}

function getFieldName(e) {
    return $("input[name='fieldName']", e)[0].value
}

function setFieldName(e, t) {
    $("input[name='fieldName']", t)[0].value = e
}

function focusInput(e) {
    $("input[name='fieldName']", $(e))[0].focus()
}

function genFieldConfigObj(e) {
    var t = JSON.parse(JSON.stringify(fieldConfigObj))
        , i = getFieldName(e)
        , n = getRowFieldId(e);
    return t.id = n,
        t.name = i,
        t.selectors = "",
        t
}

function resetTemplate(e) {
    e.removeAttr("style"),
        e.removeAttr("id"),
        $("input:text", e).val("");
    var t = "field-id-" + ++idOrder
        , i = "field_" + idOrder;
    $("input[name='rowFieldId']", e).val(t),
        $("input[name='fieldName']", e)[0].value = i,
        $("input[name='fieldName']", e).attr("value", i)
}

function upSetConfigMap(e) {
    var t = getRowFieldId(e)
        , i = genFieldConfigObj(e);
    return allFieldConfigs[t] = i,
        i
}

function getCurrFieldConfig() {
    if ($currTr)
        return getExistFieldConfig($currTr);
    alert("请选择要复制的字段，鼠标点一下字段名输入框即可")
}

function getExistFieldConfig(e) {
    if (e) {
        var t = getRowFieldId(e);
        return allFieldConfigs[t]
    }
    alert("获取指定行配置，行对象为空")
}

function getCurrFieldName() {
    return currFieldConfig && currFieldConfig.name ? currFieldConfig.name : ""
}

function getCurrFieldSelectors() {
    return currFieldConfig && currFieldConfig.selectors ? currFieldConfig.selectors : ""
}

function loadUrl(e) {
    var t = $("#pageUrl").val();
    if (!t) return !1;
    if (!isHttpUrl(t)) return layer.alert('"典型页面网址"必须以http://或https://开头'), $("#pageUrl").focus(), !1;
    var i = {url: t, isNeedLazy: $("#ajaxPage").prop("checked")};

    layui.use('layer', function () {
        var layer = layui.layer;
        // 打开遮罩
        layer.msg('加载中', {
            icon: 16
            , shade: ["0.5", "gray"]
        });
    });

    $.ajax({
        url: "/extractor/xpath/loadHtml", data: i, async: !0, success: function (e) {
            1 == e.rs ? e.data && showUrlHtml(e.data) : showMsgErr(e.msg)
            setTimeout(function () {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    // 关闭遮罩
                    layer.closeAll('loading');
                });
            }, 2000);
        }
    })
}

function loadUrlWithLazy(e) {
    var t = $("#pageUrl").val();
    if (!t) return !1;
    if (!isHttpUrl(t)) return layer.alert('"典型页面网址"必须以http://或https://开头'), $("#pageUrl").focus(), !1;
    var i = {url: t, isNeedLazy: true};

    layui.use('layer', function () {
        var layer = layui.layer;
        // 打开遮罩
        layer.msg('加载中', {
            icon: 16
            , shade: ["0.5", "gray"]
        });
    });

    $.ajax({
        url: "/extractor/xpath/loadHtml", data: i, async: !0, success: function (e) {
            1 == e.rs ? e.data && showUrlHtml(e.data) : showMsgErr(e.msg)
            setTimeout(function () {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    // 关闭遮罩
                    layer.closeAll('loading');
                });
            }, 2000);
        }
    })
}

function showUrlHtml(e) {
    try {
        var t = e;
        showHtml(t = (t = (t = t.replace(/class=\"\"/, " ")).replace(/\<\/head\>/g, '<link rel="stylesheet" type="text/css" href="' + homeUrl + '/toolbox/xpath/css/iframecontext.css"/>\x3c!--[if lte IE 9]><link rel="stylesheet" type="text/css" href="http://52tujie.com/toolbox/xpath/css/iframecontext.ie.css"/><![endif]--\x3e</head>')).replace(/\<\/body\>/g, extractorTip + '<script type="text/javascript">var urlHome="";<\/script><script type="text/javascript" src="' + homeUrl + '/toolbox/xpath/js/jquery-1.2.1.min.js"><\/script></body>'))
    } catch (e) {
    }
}

function showHtml(e) {
    try {
        var t = $("#ifr")[0];
        if (testSrcdoc()) t.srcdoc = e; else {
            t.setAttribute("srcdoc", e);
            var i = "javascript: window.frameElement.getAttribute('srcdoc');";
            t.setAttribute("src", i), t.contentWindow && (t.contentWindow.location = i)
        }
    } catch (e) {
    }
}

function testSrcdoc() {
    return "srcdoc" in document.createElement("iframe")
}

function isHttpUrl(e) {
    return !!e && !(!e.startsWith("http://") && !e.startsWith("https://"))
}

function setPageType(e) {
    pageType = e
}

function getPageType() {
    return pageType
}

function getUseLink() {
    return !!currFieldConfig && currFieldConfig.useLink
}

function useLinkAction(e) {
    if (currFieldConfig.selectors) {
        var t = $(e).prop("checked");
        t && (currFieldConfig.useImg = !1,
            dealCheckBox("useImg", !1)),
            useHtmlAction(t),
            t ? changeCurrValueType("attr", "href") : changeCurrValueType("text", "")
    }
}

function changeCurrValueType(e, t) {
    currFieldConfig.valueType = e,
        initChangeValueType(e, t)
}

function mutiValueAction(e) {
    var t = $(e).prop("checked");
    t && (setCheckBox("groupSelect", !0),
        currFieldConfig.groupSelect = t,
        saveCurrFieldConfig(),
        runIfrFun("setGroupSelect", t))
}

function useImgAction(e) {
    var t = $(e).prop("checked");
    currFieldConfig.useImg = t,
    t && (setCheckBox("useHtml", !0),
        dealCheckBox("useLink", !1),
        currFieldConfig.useLink = !t,
        currFieldConfig.useHtml = t,
        saveCurrFieldConfig()),
        useHtmlAction(t)
}

function setAndChangeCheckBox(e, t) {
    setCheckBox(e, t),
        currFieldConfig[e] = t,
        saveCurrFieldConfig()
}

function saveCurrFieldConfig() {
    currFieldConfig.selectors = $("#xpathValue").val(),
        saveCurrHtmlEles(),
        allFieldConfigs[currFieldConfig.id] = currFieldConfig
}

function switchHtmlTagdiv(e) {
    initHtmlTags(currFieldConfig.htmlEles),
        e ? $(".ts-htmlTag-div").css("display", "block") : $(".ts-htmlTag-div").css("display", "none")
}

function saveCurrHtmlEles() {
    var e = getCheckBox("htmlEleGroup", $(".ts-htmlTag-items-div"))
        , t = "";
    e && e.length > 0 && (t = e.join(",")),
        currFieldConfig.htmlEles = t
}

function getCheckBox(e, t) {
    var i = []
        , n = [];
    return n = t ? $("input[type='checkbox'][name='" + e + "']:checked", t) : $("input[type='checkbox'][name='" + e + "']:checked"),
        $.each(n, function () {
            i.push($(this).val())
        }),
        i
}

function saveSelect(e, t) {
    pageType == listType && !extractorEdited && currFieldConfig && currFieldConfig.selectors && e ? layer.confirm('是否重新选择？只需在页面中点击"两个不同链接"', function (i) {
        i ? clearAndReset() : saveSelectDao(e, t)
    }) : mutiPagerSwitch ? savaSelectorPage(e, t) : saveSelectDao(e, t),
        extractorEdited = !0
}

function savaSelectorPage(e, t) {
    currFieldConfig.pageSelector = e,
        setPageSelector(e);
    if (e == "") {
        setAndChangeCheckBox("pageMutiValue", 0);
        setAndChangeCheckBox("pageGroupSelect", 0);
    }
    saveCurrFieldConfig();
    e ? showPageFieldValue(genExtractValueArrForPage(t)) : removePageFieldValues()
}

function saveSelectDao(e, t) {
    if ($.isEmptyObject(allFieldConfigs) && (addNewRow(),
        locationIfrSelector(e)),
        currFieldConfig.selectors = e,
        setXpathValue(e),
        saveCurrFieldConfig(),
        e) {
        var i = genExtractValueArr(currFieldConfig, t, currFieldConfig.useHtml, currFieldConfig.useLink);
        saveCurrFieldConfig(),
            showFieldValue(i)
    } else
        removeFieldValues();
    initFieldConfigShow(currFieldConfig),
        resetFieldIconCurr()
}

function resetFieldIconCurr() {
    resetFieldIcon($currTr)
}

function setCheckBox(e, t) {
    t ? $("#" + e).prop("checked", !0) : $("#" + e).attr("checked", !1)
}

function clearAndReset() {
    clearRow(),
        clearIframe(),
    pageType == listType && (currFieldConfig.useLink = !0, currFieldConfig.required = !0);
    var e = currFieldConfig.name;
    "content" != e && "内容" != e || (currFieldConfig.useHtml = !0,
        currFieldConfig.valueType = "html",
        currFieldConfig.dela = 2),
        saveCurrFieldConfig(),
        initFieldConfigShow(currFieldConfig),
        resetFieldIconCurr()
}

function clearRow() {
    var e = currFieldConfig.name
        , t = currFieldConfig.id
        , i = jsonClone(fieldConfigObj);
    i.name = e,
        i.id = t,
        currFieldConfig = i,
        setXpathValue(""),
        removeFieldValues(),
        removePageFieldValues(),
        saveCurrFieldConfig(),
        initFieldConfigShow(i),
        showToAllFieldsDataTable(),
        showMsgSuc("字段：" + e + "：配置清除成功！")
}

function initFieldConfigShow(e) {
    e || (e = fieldConfigObj),
        setTitle(e.name),
        dealCheckBox("required", e.required),
        dealCheckBox("delaTxt", e.delaTxt > 0),
        dealCheckBox("dela", e.dela > 0),
        dealCheckBox("dela-keeptxt", 2 == e.dela),
        dealCheckBox("useHtml", e.useHtml),
        dealCheckBox("cleanHtml", e.cleanHtml),
        dealCheckBox("keepAlt", e.keepAlt),
        dealCheckBox("useLink", e.useLink),
        dealCheckBox("useImg", e.useImg),
        dealCheckBox("mutiValue", e.mutiValue),
        dealCheckBox("groupSelect", e.groupSelect),
        $("#selectors").val(e.selectors),
        setXpathValue(e.selectors),
        setPageSelector(e.pageSelector),
        initMutiPagrValue();
    if (e.useLink) {
        e.valueType = "attr",
            e.attrName = "href"
    }
    initChangeValueType(e.valueType, e.attrName);
    initHtmlTags(e.htmlEles)
}

function setTitle(e) {
    e || (e = ""),
        $(".ts-show-fieldName").html("<Strong>" + e + "</Strong>"),
        runIfrFun("changeFieldName", e)
}

function runIfrFun(method, para1, para2, para3) {
    var ct = "CONTENT".toLowerCase();
    try {
        var cw = ct + win;
        if (eval('$("#ifr")[0].' + cw + "." + method)) {
            var func = eval('$("#ifr")[0].' + cw + "." + method);
            return func.call(func, para1, para2, para3)
        }
    } catch (e) {
    }
}

function dealCheckBox(e, t) {
    t ? $("input[type='checkbox'][name='" + e + "']").prop("checked", !0) : $("input[type='checkbox'][name='" + e + "']").attr("checked", !1);
}

function setXpathValue(e) {
    $("#xpathValue").val(e)
}

function setPageSelector(e) {
    $("#pageSelector").val(e)
}

function initChangeValueType(e, t) {
    $("#valueType").val(e),
    t || (t = ""),
        $("#attrName").val(t),
        currFieldConfig.attrName = t;
    "attr" == e ? $(".ts-attrValue-div").css("display", "block") : $(".ts-attrValue-div").css("display", "none"),
    "html" != e && dealCheckBox("useHtml", !1)
}

function initMutiPagrValue() {
    if (!currFieldConfig)
        return !1;
    dealCheckBox("mutiPage", currFieldConfig.mutiPage),
        showMutiPage(1 == currFieldConfig.mutiPage),
        $("#pageSelector").val(currFieldConfig.pageSelector),
        checkRadio("pageSave", currFieldConfig.pageSave),
        $("#pageConcat").val(currFieldConfig.pageConcat),
        $("#maxPage").val(currFieldConfig.maxPage),
        $("#urlContain").val(currFieldConfig.urlContain)
}

function showMutiPage(e) {
    e ? $(".ts-setMutiPager-div").removeClass("hide") & $(".page-data-panel").removeClass("hide") : $(".ts-setMutiPager-div").addClass("hide") & $(".page-data-panel").addClass("hide")
}

function checkRadio(e, t) {
    $("input[type='radio'][name='" + e + "'][value='" + t + "']").prop("checked", !0)
}

function getCheckRadio(e, t) {
    return t ? $("input[type='radio'][name='" + e + "']:checked", t).val() : $("input[type='radio'][name='" + e + "']:checked").val()
}

function getRadioCheckObjy(e, t) {
    return t ? $("input[type='radio'][name='" + e + "']:checked", t) : $("input[type='radio'][name='" + e + "']:checked")
}

function initHtmlTags(e) {
    $("input[name='htmlEleGroup']:checkbox", $(".ts-htmlTag-items-div")).each(function () {
        $(this).prop("checked", !1)
    }),
    e && setCheckBoxGroup("htmlEleGroup", e.split(","))
}

function setCheckBoxGroup(e, t) {
    if (t && t.length && t.length > 0)
        for (var i = 0, n = t.length; i < n; i++)
            $("input[type='checkbox'][name='" + e + "'][value='" + t[i] + "']").prop("checked", !0)
}

function initStart() {
    currFieldConfig ? setXpathValue(currFieldConfig.selectors) : addNewRow(),
        pageType == listType ? dealListPage() : pageType == detailType && dealDetailPage(),
        $("#pageType").val(pageType),
    isConfiger || loadUrl()
}

function dealListPage() {
    hiddenElement("required-lb", !0),
        hiddenElement("useHtml-lb", !0),
        hiddenElement("mutiValue-lb", !0),
        hiddenElement("useImg-lb", !0),
        hiddenElement("delaTxt-lb", !0),
        hiddenElement("dela-lb", !0),
        hiddenElement("mutiPage-lb", !0),
        hiddenElementWithClass("ts-advDataDeal", !0),
        hiddenElementWithClass("ts-htmlTag-select", !0),
        hiddenElementWithClass("ts-delImgItem", !0),
        hiddenElementWithClass("ts-delAsItem", !0),
        // hiddenElement("fields-table", !0),
        // hiddenElement("field-Define", !0),
        hiddenElement("current-field-config", !0)


}

function dealDetailPage() {
    hiddenElement("useLink-lb", !0),
        hiddenElementWithClass("ts-advDataDeal", !0),
        hiddenElementWithClass("ts-htmlTag-select", !0),
        hiddenElementWithClass("ts-delImgItem", !0),
        hiddenElementWithClass("ts-delAsItem", !0),
        hiddenElement("groupSelect-lb", !0)
}

function hiddenElement(e, t) {
    t ? $("#" + e).hide() : $("#" + e).show()
}

function hiddenElementWithClass(e, t) {
    t ? $("." + e).hide() : $("." + e).show()
}

function addNewRowCommon(e, t) {
    for (var i in allFieldConfigs)
        if (allFieldConfigs[i].name == e)
            return showMsgErr("字段名已存在，不能再添加同名字段！"),
                !1;
    var n = {};
    (n = jsonClone(fieldConfigObj)).name = e,
    t && (n.useHtml = !0,
        n.valueType = "html");
    var a = "";
    "description" == e ? (a = descriptionSelector,
        n.selectors = descriptionSelector,
        n.isMeta = !0,
        n.valueType = "attr",
        n.attrName = "content") : "keywords" == e && (a = keywordsSelector,
        n.isMeta = !0,
        n.selector = keywordsSelector,
        n.valueType = "attr",
        n.attrName = "content");
    var o = addInitRow(n);
    $currTr = o,
        upSetConfigMap(o),
        currFieldConfig = n,
        $("#xpathValue").val(a),
        saveCurrFieldConfig(),
        initFieldConfigShow(currFieldConfig),
        setFieldName(currFieldConfig.name, o),
        focusInput(o),
        hlCurrTr(o),
        clearIframe()
}

function addNewRow() {
    var e = addRow();
    $currTr = e,
        upSetConfigMap(e),
        (currFieldConfig = getCurrFieldConfig()).name = getFieldName(e),
        currFieldConfig.selectors = "",
        $("#xpathValue").val(""),
    pageType == listType && (currFieldConfig.useLink = !0, currFieldConfig.required = !0),
        saveCurrFieldConfig(),
        initFieldConfigShow(currFieldConfig),
        setFieldName(currFieldConfig.name, e),
        focusInput(e),
        hlCurrTr(e),
        clearIframe()
}

function clearIframe() {
    runIfrFun("clearAll")
}

function hlCurrTr(e) {
    $("#fields-table>tbody tr").removeClass(trHlClass),
        $(e).addClass(trHlClass)
}

function addInitRow(e) {
    var t = addRow();
    setFieldName(e.name, t);
    var i = getRowFieldId(t)
        , n = getRowFieldId(t);
    return e.id = n,
        allFieldConfigs[i] = e,
        resetFieldIcon(t),
        t
}

function resetFieldIcon(e) {
    var t = iconSuc
        , i = getRowFieldId(e)
        , n = allFieldConfigs[i];
    if (!n)
        return showMsgErr("获取不到配置字段！"),
            !1;
    var a = $("div.field-status>i", e)
        , o = "";
    n.selectors || (t = iconWarn,
        o = "未配置xpath规则或随机值"),
    n.isMeta && (n.selectors.startsWith("/html/head") || n.selectors.startsWith("//meta")) && (t = iconMeta,
        o = "该字段页面数据不可见，但服务器可以处理。"),
    "random" == n.valueType && (t = iconSuc,
        o = "随机值"),
        a.attr("class", t),
        a.attr("data-rel", "tooltip"),
        a.attr("data-original-title", o)
}

function addRow() {
    var e = initTemplate("fields-table");
    return $("#fields-table>tbody tr:last").after(e),
        e
}

function initTemplate(e) {
    var t = $("#" + e + ">tbody>tr:first").clone(!0, !0);
    return resetTemplate(t),
        t
}

function e(e) {
    var t = e.attr("useHtml")
        , i = !(!t || "1" != t);
    addNewRowCommon(e.attr("fieldValue"), i)
}

function t(e, t) {
    var i = homeUrl + "/task/extrator/" + e + "/" + taskId;
    t && (i = i + "?testUrl=" + i),
        window.open(i)
}

function h() {
    initDataDealValue(),
        initDefaultValue(),
        initFileDown(),
        initReplaces(),
        initDataDeals(),
        initRegex(),
        initSelector(),
        initHtmlTags(currFieldConfig.htmlEles)
}

function initSelector() {
    $("#ts-selectors").text(currFieldConfig.selectors),
        $("#xpathValue").val(currFieldConfig.selectors),
        $("#ts-fieldValue").html(""),
        $("#ts-fieldValue").html(genCurrFieldValueArr().join("\n"))
}

function initDataDeals() {
    emptyDataDeals();
    var e = currFieldConfig.dataDealVos;
    if (e && e.length > 0)
        for (var t = 0, i = e.length; t < i; t++) {
            var n = e[t]
                , a = addRowByDataDealType(n.typeStr);
            if ("delTag" == n.typeStr) {
                $("select[name=posType]", a).val(n.posType),
                    $("input[name=delCount]", a).val(n.delCount),
                    $("select[name=tagName]", a).val(n.tagName),
                    $("select[name=tagName] option", a).each(function (e, t) {
                        $.trim(t.value) == n.tagName && (this.selected = !0)
                    }),
                    $("select[name=tagName]", a).multiselect("refresh");
                var o = 1 == n.leftText;
                $("input[type='checkbox'][name=leftText]", a).prop("checked", o)
            }
            $("input[name=sortNo]", a).val(n.sortNo),
            t == i - 1 && (advSortNo = parseInt(n.sortNo))
        }
    else
        addRowByDataDealType("delTag")
}

function addRowReplace() {
    var e = initTemplateReplace("replace-table");
    return $("#replace-table>tbody tr:last").after(e),
        e
}

function initTemplateReplace(e) {
    var t = $("#" + e + ">tbody>tr:first").clone(!0, !0);
    return resetTemplateReplace(t),
        t
}

function resetTemplateReplace(e) {
    e.removeAttr("style"),
        e.removeAttr("id"),
        $("input:text", e).val("")
}

function addRowByDataDealType(e) {
    return addRowAdv(getDataDealTrIdByType())
}

function getDataDealTrIdByType(e) {
    return "trCloneDelHtml"
}

function addRowAdv(e) {
    var t = initTemplateByTrId(e);
    return initMutiSelected("select[name=tagName]", t),
        $("#adv-deal-table>tbody tr:last").after(t),
        t
}

function initMutiSelected(e, t) {
    $(e, t).multiselect("destroy").multiselect({
        nonSelectedText: "--请选择--",
        enableFiltering: !0,
        buttonClass: "btn btn-white btn-primary",
        maxHeight: 350,
        includeSelectAllOption: !0,
        numberDisplayed: 5,
        templates: {
            button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"><span class="multiselect-selected-text"></span> &nbsp;<b class="fa fa-caret-down"></b></button>',
            ul: '<ul class="multiselect-container dropdown-menu"></ul>',
            filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
            filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
            li: '<li><a tabindex="0"><label></label></a></li>',
            divider: '<li class="multiselect-item divider"></li>',
            liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
        }
    })
}

function initTemplateByTrId(e) {
    var t = $("#" + e).clone(!0, !0);
    return resetTemplateAdvDataDeal(t),
        t
}

function resetTemplateAdvDataDeal(e) {
    e.removeAttr("style"),
        e.removeAttr("id"),
        $("input:text", e).val(""),
        advSortNo += 1,
        $("input[name='sortNo']", e).val(advSortNo)
}

function emptyDataDeals() {
    $("#" + dataDealTableId + ">tbody tr:gt(0)").each(function () {
        $(this).remove()
    })
}

function initReplaces() {
    emptyReplaces();
    var e = currFieldConfig.replaces;
    if (e && e.length > 0)
        for (var t = 0, i = e.length; t < i; t++) {
            var n = e[t]
                , a = addRowReplace();
            $("input[name=from]", a).val(n.from),
                $("input[name=to]", a).val(n.to);
            var o = 1 == n.reg;
            $("input[type='checkbox'][name=reg]", a).prop("checked", o)
        }
    else
        addRowReplace()
}

function emptyReplaces() {
    $("#replace-table>tbody tr:not(:first)").each(function () {
        $(this).remove()
    })
}

function initFileDown() {
    checkRadio("fileSaveType", currFieldConfig.fileSaveType),
        checkRadio("storageType", storageType),
        $("#httpPrefix").val(fileDownConfig.httpPrefix)
}

function initDefaultValue() {
    $("#ts-defaultValue").val(currFieldConfig.defaultValue),
        $("#imgAttr").val(currFieldConfig.imgAttr),
        $("#concatDelimiter").val(currFieldConfig.concatDelimiter),
        $("#valueType").val(currFieldConfig.valueType),
        $("#attrName").val(currFieldConfig.attrName)
}

function initDataDealValue() {
    checkRadio("delAllImg", currFieldConfig.delAllImg),
        initCheckBoxItemByName(currFieldConfig.delImg, "delImgItem"),
        checkRadio("dela", currFieldConfig.dela),
        initCheckBoxItemByName(currFieldConfig.delAs, "delAsItem"),
        dealCheckBox("pType", currFieldConfig.pType),
        $("#preTxt").val(currFieldConfig.preTxt),
        $("#tailTxt").val(currFieldConfig.tailTxt),
        checkRadio("randType", currFieldConfig.randType);
    var e = getRadioCheckObjy("randType");
    e && changeRandTypeShow(e.attr("data-show")),
        $("#minRd").val(currFieldConfig.minRd),
        $("#maxRd").val(currFieldConfig.maxRd),
        $("#minRdtStr").val(currFieldConfig.minRdtStr),
        $("#maxRdtStr").val(currFieldConfig.maxRdtStr),
        $("#timeFmt").val(currFieldConfig.timeFmt),
        $("#txtRd").val(currFieldConfig.txtRd),
        $("#lenType").val(currFieldConfig.lenType),
        $("#lenLimit").val(currFieldConfig.lenLimit),
        checkRadio("filterType", 0 == currFieldConfig.filterType ? 1 : currFieldConfig.filterType),
        $("#noInclude").val(currFieldConfig.noInclude),
        $("#mustInclude").val(currFieldConfig.mustInclude)
}

function changeRandTypeShow(e) {
    showChangeByClass(e, "ts-random-int-div"),
        showChangeByClass(e, "ts-random-time-div"),
        showChangeByClass(e, "ts-random-str-div")
}

function showChangeByClass(e, t) {
    e == t ? $("." + t).css("display", "block") : $("." + t).css("display", "none")
}

function initCheckBoxItemByName(e, t) {
    if (e) {
        dealCheckBox(t, !1);
        for (var i = e.split(","), n = 0, a = i.length; n < a; n++)
            setCheckBoxByName(t, i[n])
    } else
        dealCheckBox(t, !1)
}

/**
 * util
 */
function jsonClone(e) {
    return JSON.parse(JSON.stringify(e))
}

function isInArray(e, t) {
    return $.inArray(t, e) >= 0
}

function html2Escape(e) {
    return e.replace(/[<>&"]/g, function (e) {
        return {
            "<": "&lt;",
            ">": "&gt;",
            "&": "&amp;",
            '"': "&quot;"
        }[e]
    })
}

function str2Num(e) {
    return e ? parseInt(e) : 0
}

function $$$(e) {
    return document.getElementById(e)
}

function isURL(e) {
    return !!new RegExp("^((https|http|ftp|rtsp|mms)?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$").test(e)
}

/**
 * 弹窗
 */
function showMsgErr(e, t) {
    showMsg(e, "error", t)
}

function showMsgSuc(e, t) {
    showMsg(e, "success", t)
}

function showSaveSuc() {
    showMsgSuc("保存成功！")
}

function showMsg(e, t, i) {
    t == "success" ? alertMsg(true, e) : alertMsg(false, e);
    i && $("#" + i).focus();
}

function alertMsg(isSuccess, msg) {
    if (isSuccess) {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                title: '成功'
                , content: msg
            });
        });
    } else {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                title: '错误'
                , content: msg
            });
        });
    }
}

function showMsgConfirm(e, f) {
    layer.open({
        content: e,
        custom: f,
        yes: function (index) {
            f(e)
            layer.close(index)
        }
    });
}

function showBoxContent(e, t, i) {
    var n = '<div id="' + e + '" class="modal fade" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-body modal-body-alert"><div class="modal-alert-title">' + t + '</div> <i class="icon icon-alert-close" data-dismiss="modal"></i>' + i + "</div></div></div></div>";
    $("#" + e).length > 0 && $("#" + e).remove(),
        $("body").append(n),
        $("#" + e).modal()
}

function reloadWin() {
    window.location.href = window.location.href,
        window.location.reload
}

function reloadOpener() {
    opener && opener.location && opener.location.reload()
}

function genCurrFieldValueArr() {
    return genExtractValueArr(currFieldConfig, extractElementsCh(currFieldConfig.selectors), currFieldConfig.useHtml, currFieldConfig.useLink, currFieldConfig.valueType, currFieldConfig.attrName)
}

/**
 * 正则表达式
 */
function initRegex() {
    setTitle(currFieldConfig.name),
        $("#ts-fieldValue-regex").html(initFieldValueRegex()),
        $("#ts-match-regex").val(currFieldConfig.matchRegex),
        $("#ts-match-replace").val(currFieldConfig.matchReplace),
        $("#ts-matchGp").val(currFieldConfig.matchGp),
        $("#ts-matchSplit").val(currFieldConfig.matchSplit),
        testRegex(!1),
        testRegexMatchGp(!1)
}

function saveRegex() {
    currFieldConfig.matchRegex = $("#ts-match-regex").val(),
        currFieldConfig.matchReplace = $("#ts-match-replace").val(),
        currFieldConfig.matchGp = $("#ts-matchGp").val(),
        currFieldConfig.matchSplit = $("#ts-matchSplit").val(),
        saveCurrFieldConfig()
}

function saveRegexAndShow() {
    saveRegex(),
        initCurrTrShow()
}

function initCurrTrShow() {
    initTrShow($currTr)
}

function callByIframeInit() {
    return $currTr && (initTrShow($currTr),
        focusInput($currTr),
        hlCurrTr($currTr),
        initCounterAfterIframe()),
        !0
}

function initCounterAfterIframe() {
}

function initFieldValueRegex() {
    var n = jsonClone(currFieldConfig);
    n.matchRegex = '',
        n.matchReplace = '',
        n.matchGp = '',
        n.matchSplit = '';
    return genFinalDatasString(currFieldConfig.selectors, n);
}

function testRegex(e) {
    var t = $("#ts-match-regex").val();
    if (e && !t)
        return showMsgErr("请填写'将匹配的内容'"),
            !1;
    {
        if (t) {
            var i = $("#ts-match-replace").val()
                , n = jsonClone(currFieldConfig);
            n.matchRegex = t,
                n.matchReplace = i;
            var a = genFinalDatasString(currFieldConfig.selectors, n);
            return $("#ts-regex-result").html(genRegexValues(a)),
                !0
        }
        $("#ts-regex-result").html("")
    }
}

function testRegexMatchGp(e) {
    var t = $("#ts-matchGp").val();
    if (e && !t)
        return showMsgErr("请填写'正则捕获组'"),
            !1;
    {
        if (t) {
            var i = $("#ts-matchSplit").val()
                , n = jsonClone(currFieldConfig);
            n.matchGp = t,
                n.matchSplit = i;
            var a = genFinalDatasString(currFieldConfig.selectors, n);
            return $("#ts-regex-result").html(genRegexValues(a)),
                !0
        }
        $("#ts-regex-result").html("")
    }
}

function setDefRegex(e) {
    $("#ts-match-regex").val($(e).attr("data-regex")),
        testRegex()
}

function setDefRegexGroup(e) {
    $("#ts-matchGp").val($(e).attr("data-regex-group")),
        $("#ts-matchSplit").val($(e).attr("regex-group-splitter")),
        testRegexMatchGp(!0)
}

function genRegexValues(e) {
    if (!e || 0 == e.length)
        return "";
    for (var t = "", i = 0, n = e.length; i < n; i++)
        t += e[i];
    return t
}

/**dialog and ip proxy**/
!function (e, t) {
    "use strict";
    "function" == typeof define && define.amd ? define(["jquery"], t) : "object" == typeof exports ? module.exports = t(require("jquery")) : e.bootbox = t(e.jQuery)
}(this, function e(t, i) {
    "use strict";

    function n(e) {
        var t = m[p.locale];
        return t ? t[e] : m.en[e]
    }

    function a(e, i, n) {
        e.stopPropagation(),
            e.preventDefault(),
        t.isFunction(n) && !1 === n.call(i, e) || i.modal("hide")
    }

    function o(e) {
        var t, i = 0;
        for (t in e)
            i++;
        return i
    }

    function r(e, i) {
        var n = 0;
        t.each(e, function (e, t) {
            i(e, t, n++)
        })
    }

    function s(e) {
        var i, n;
        if ("object" != typeof e)
            throw new Error("Please supply an object of options");
        if (!e.message)
            throw new Error("Please specify a message");
        return (e = t.extend({}, p, e)).buttons || (e.buttons = {}),
            i = e.buttons,
            n = o(i),
            r(i, function (e, a, o) {
                if (t.isFunction(a) && (a = i[e] = {
                    callback: a
                }),
                "object" !== t.type(a))
                    throw new Error("button with key " + e + " must be an object");
                a.label || (a.label = e),
                a.className || (a.className = 2 >= n && o === n - 1 ? "btn-primary" : "btn-default")
            }),
            e
    }

    function l(e, t) {
        var i = e.length
            , n = {};
        if (1 > i || i > 2)
            throw new Error("Invalid argument length");
        return 2 === i || "string" == typeof e[0] ? (n[t[0]] = e[0],
            n[t[1]] = e[1]) : n = e[0],
            n
    }

    function c(e, i, n) {
        return t.extend(!0, {}, e, l(i, n))
    }

    function u(e, t, i, n) {
        return h(c({
            className: "bootbox-" + e,
            buttons: d.apply(null, t)
        }, n, i), t)
    }

    function d() {
        for (var e = {}, t = 0, i = arguments.length; i > t; t++) {
            var a = arguments[t]
                , o = a.toLowerCase()
                , r = a.toUpperCase();
            e[o] = {
                label: n(r)
            }
        }
        return e
    }

    function h(e, t) {
        var n = {};
        return r(t, function (e, t) {
            n[t] = !0
        }),
            r(e.buttons, function (e) {
                if (n[e] === i)
                    throw new Error("button key " + e + " is not allowed (options are " + t.join("\n") + ")")
            }),
            e
    }

    var f = {
        dialog: "<div class='bootbox modal' tabindex='-1' role='dialog'><div class='modal-dialog'><div class='modal-content'><div class='modal-body'><div class='bootbox-body'></div></div></div></div></div>",
        header: "<div class='modal-header'><h4 class='modal-title'></h4></div>",
        footer: "<div class='modal-footer'></div>",
        closeButton: "<button type='button' class='bootbox-close-button close' data-dismiss='modal' aria-hidden='true'>&times;</button>",
        form: "<form class='bootbox-form'></form>",
        inputs: {
            text: "<input class='bootbox-input bootbox-input-text form-control' autocomplete=off type=text />",
            textarea: "<textarea class='bootbox-input bootbox-input-textarea form-control'></textarea>",
            email: "<input class='bootbox-input bootbox-input-email form-control' autocomplete='off' type='email' />",
            select: "<select class='bootbox-input bootbox-input-select form-control'></select>",
            checkbox: "<div class='checkbox'><label><input class='bootbox-input bootbox-input-checkbox' type='checkbox' /></label></div>",
            date: "<input class='bootbox-input bootbox-input-date form-control' autocomplete=off type='date' />",
            time: "<input class='bootbox-input bootbox-input-time form-control' autocomplete=off type='time' />",
            number: "<input class='bootbox-input bootbox-input-number form-control' autocomplete=off type='number' />",
            password: "<input class='bootbox-input bootbox-input-password form-control' autocomplete='off' type='password' />"
        }
    }
        , p = {
        locale: "en",
        backdrop: "static",
        animate: !0,
        className: null,
        closeButton: !0,
        show: !0,
        container: "body"
    }
        , g = {};
    g.alert = function () {
        var e;
        if ((e = u("alert", ["ok"], ["message", "callback"], arguments)).callback && !t.isFunction(e.callback))
            throw new Error("alert requires callback property to be a function when provided");
        return e.buttons.ok.callback = e.onEscape = function () {
            return !t.isFunction(e.callback) || e.callback.call(this)
        }
            ,
            g.dialog(e)
    }
        ,
        g.confirm = function () {
            var e;
            if (e = u("confirm", ["cancel", "confirm"], ["message", "callback"], arguments),
                e.buttons.cancel.callback = e.onEscape = function () {
                    return e.callback.call(this, !1)
                }
                ,
                e.buttons.confirm.callback = function () {
                    return e.callback.call(this, !0)
                }
                ,
                !t.isFunction(e.callback))
                throw new Error("confirm requires a callback");
            return g.dialog(e)
        }
        ,
        g.prompt = function () {
            var e, n, a, o, s, l, u;
            if (o = t(f.form),
                n = {
                    className: "bootbox-prompt",
                    buttons: d("cancel", "confirm"),
                    value: "",
                    inputType: "text"
                },
                e = h(c(n, arguments, ["title", "callback"]), ["cancel", "confirm"]),
                l = e.show === i || e.show,
                e.message = o,
                e.buttons.cancel.callback = e.onEscape = function () {
                    return e.callback.call(this, null)
                }
                ,
                e.buttons.confirm.callback = function () {
                    var i;
                    switch (e.inputType) {
                        case "text":
                        case "textarea":
                        case "email":
                        case "select":
                        case "date":
                        case "time":
                        case "number":
                        case "password":
                            i = s.val();
                            break;
                        case "checkbox":
                            var n = s.find("input:checked");
                            i = [],
                                r(n, function (e, n) {
                                    i.push(t(n).val())
                                })
                    }
                    return e.callback.call(this, i)
                }
                ,
                e.show = !1,
                !e.title)
                throw new Error("prompt requires a title");
            if (!t.isFunction(e.callback))
                throw new Error("prompt requires a callback");
            if (!f.inputs[e.inputType])
                throw new Error("invalid prompt type");
            switch (s = t(f.inputs[e.inputType]),
                e.inputType) {
                case "text":
                case "textarea":
                case "email":
                case "date":
                case "time":
                case "number":
                case "password":
                    s.val(e.value);
                    break;
                case "select":
                    var p = {};
                    if (u = e.inputOptions || [],
                        !t.isArray(u))
                        throw new Error("Please pass an array of input options");
                    if (!u.length)
                        throw new Error("prompt with select requires options");
                    r(u, function (e, n) {
                        var a = s;
                        if (n.value === i || n.text === i)
                            throw new Error("given options in wrong format");
                        n.group && (p[n.group] || (p[n.group] = t("<optgroup/>").attr("label", n.group)),
                            a = p[n.group]),
                            a.append("<option value='" + n.value + "'>" + n.text + "</option>")
                    }),
                        r(p, function (e, t) {
                            s.append(t)
                        }),
                        s.val(e.value);
                    break;
                case "checkbox":
                    var m = t.isArray(e.value) ? e.value : [e.value];
                    if (!(u = e.inputOptions || []).length)
                        throw new Error("prompt with checkbox requires options");
                    if (!u[0].value || !u[0].text)
                        throw new Error("given options in wrong format");
                    s = t("<div/>"),
                        r(u, function (i, n) {
                            var a = t(f.inputs[e.inputType]);
                            a.find("input").attr("value", n.value),
                                a.find("label").append(n.text),
                                r(m, function (e, t) {
                                    t === n.value && a.find("input").prop("checked", !0)
                                }),
                                s.append(a)
                        })
            }
            return e.placeholder && s.attr("placeholder", e.placeholder),
            e.pattern && s.attr("pattern", e.pattern),
            e.maxlength && s.attr("maxlength", e.maxlength),
                o.append(s),
                o.on("submit", function (e) {
                    e.preventDefault(),
                        e.stopPropagation(),
                        a.find(".btn-primary").click()
                }),
                (a = g.dialog(e)).off("shown.bs.modal"),
                a.on("shown.bs.modal", function () {
                    s.focus()
                }),
            !0 === l && a.modal("show"),
                a
        }
        ,
        g.dialog = function (e) {
            e = s(e);
            var n = t(f.dialog)
                , o = n.find(".modal-dialog")
                , l = n.find(".modal-body")
                , c = e.buttons
                , u = ""
                , d = {
                onEscape: e.onEscape
            };
            if (t.fn.modal === i)
                throw new Error("$.fn.modal is not defined; please double check you have included the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ for more details.");
            if (r(c, function (e, t) {
                u += "<button data-bb-handler='" + e + "' type='button' class='btn " + t.className + "'>" + t.label + "</button>",
                    d[e] = t.callback
            }),
                l.find(".bootbox-body").html(e.message),
            !0 === e.animate && n.addClass("fade"),
            e.className && n.addClass(e.className),
                "large" === e.size ? o.addClass("modal-lg") : "small" === e.size && o.addClass("modal-sm"),
            e.title && l.before(f.header),
                e.closeButton) {
                var h = t(f.closeButton);
                e.title ? n.find(".modal-header").prepend(h) : h.css("margin-top", "-10px").prependTo(l)
            }
            return e.title && n.find(".modal-title").html(e.title),
            u.length && (l.after(f.footer),
                n.find(".modal-footer").html(u)),
                n.on("hidden.bs.modal", function (e) {
                    e.target === this && n.remove()
                }),
                n.on("shown.bs.modal", function () {
                    n.find(".btn-primary:first").focus()
                }),
            "static" !== e.backdrop && n.on("click.dismiss.bs.modal", function (e) {
                n.children(".modal-backdrop").length && (e.currentTarget = n.children(".modal-backdrop").get(0)),
                e.target === e.currentTarget && n.trigger("escape.close.bb")
            }),
                n.on("escape.close.bb", function (e) {
                    d.onEscape && a(e, n, d.onEscape)
                }),
                n.on("click", ".modal-footer button", function (e) {
                    var i = t(this).data("bb-handler");
                    a(e, n, d[i])
                }),
                n.on("click", ".bootbox-close-button", function (e) {
                    a(e, n, d.onEscape)
                }),
                n.on("keyup", function (e) {
                    27 === e.which && n.trigger("escape.close.bb")
                }),
                t(e.container).append(n),
                n.modal({
                    backdrop: !!e.backdrop && "static",
                    keyboard: !1,
                    show: !1
                }),
            e.show && n.modal("show"),
                n
        }
        ,
        g.setDefaults = function () {
            var e = {};
            2 === arguments.length ? e[arguments[0]] = arguments[1] : e = arguments[0],
                t.extend(p, e)
        }
        ,
        g.hideAll = function () {
            return t(".bootbox").modal("hide"),
                g
        }
    ;
    var m = {
        bg_BG: {
            OK: "Ок",
            CANCEL: "Отказ",
            CONFIRM: "Потвърждавам"
        },
        br: {
            OK: "OK",
            CANCEL: "Cancelar",
            CONFIRM: "Sim"
        },
        cs: {
            OK: "OK",
            CANCEL: "Zrušit",
            CONFIRM: "Potvrdit"
        },
        da: {
            OK: "OK",
            CANCEL: "Annuller",
            CONFIRM: "Accepter"
        },
        de: {
            OK: "OK",
            CANCEL: "Abbrechen",
            CONFIRM: "Akzeptieren"
        },
        el: {
            OK: "Εντάξει",
            CANCEL: "Ακύρωση",
            CONFIRM: "Επιβεβαίωση"
        },
        en: {
            OK: "OK",
            CANCEL: "Cancel",
            CONFIRM: "OK"
        },
        es: {
            OK: "OK",
            CANCEL: "Cancelar",
            CONFIRM: "Aceptar"
        },
        et: {
            OK: "OK",
            CANCEL: "Katkesta",
            CONFIRM: "OK"
        },
        fa: {
            OK: "قبول",
            CANCEL: "لغو",
            CONFIRM: "تایید"
        },
        fi: {
            OK: "OK",
            CANCEL: "Peruuta",
            CONFIRM: "OK"
        },
        fr: {
            OK: "OK",
            CANCEL: "Annuler",
            CONFIRM: "D'accord"
        },
        he: {
            OK: "אישור",
            CANCEL: "ביטול",
            CONFIRM: "אישור"
        },
        hu: {
            OK: "OK",
            CANCEL: "Mégsem",
            CONFIRM: "Megerősít"
        },
        hr: {
            OK: "OK",
            CANCEL: "Odustani",
            CONFIRM: "Potvrdi"
        },
        id: {
            OK: "OK",
            CANCEL: "Batal",
            CONFIRM: "OK"
        },
        it: {
            OK: "OK",
            CANCEL: "Annulla",
            CONFIRM: "Conferma"
        },
        ja: {
            OK: "OK",
            CANCEL: "キャンセル",
            CONFIRM: "確認"
        },
        lt: {
            OK: "Gerai",
            CANCEL: "Atšaukti",
            CONFIRM: "Patvirtinti"
        },
        lv: {
            OK: "Labi",
            CANCEL: "Atcelt",
            CONFIRM: "Apstiprināt"
        },
        nl: {
            OK: "OK",
            CANCEL: "Annuleren",
            CONFIRM: "Accepteren"
        },
        no: {
            OK: "OK",
            CANCEL: "Avbryt",
            CONFIRM: "OK"
        },
        pl: {
            OK: "OK",
            CANCEL: "Anuluj",
            CONFIRM: "Potwierdź"
        },
        pt: {
            OK: "OK",
            CANCEL: "Cancelar",
            CONFIRM: "Confirmar"
        },
        ru: {
            OK: "OK",
            CANCEL: "Отмена",
            CONFIRM: "Применить"
        },
        sq: {
            OK: "OK",
            CANCEL: "Anulo",
            CONFIRM: "Prano"
        },
        sv: {
            OK: "OK",
            CANCEL: "Avbryt",
            CONFIRM: "OK"
        },
        th: {
            OK: "ตกลง",
            CANCEL: "ยกเลิก",
            CONFIRM: "ยืนยัน"
        },
        tr: {
            OK: "Tamam",
            CANCEL: "İptal",
            CONFIRM: "Onayla"
        },
        zh_CN: {
            OK: "OK",
            CANCEL: "取消",
            CONFIRM: "确认"
        },
        zh_TW: {
            OK: "OK",
            CANCEL: "取消",
            CONFIRM: "確認"
        }
    };
    return g.addLocale = function (e, i) {
        return t.each(["OK", "CANCEL", "CONFIRM"], function (e, t) {
            if (!i[t])
                throw new Error("Please supply a translation for '" + t + "'")
        }),
            m[e] = {
                OK: i.OK,
                CANCEL: i.CANCEL,
                CONFIRM: i.CONFIRM
            },
            g
    }
        ,
        g.removeLocale = function (e) {
            return delete m[e],
                g
        }
        ,
        g.setLocale = function (e) {
            return g.setDefaults("locale", e)
        }
        ,
        g.init = function (i) {
            return e(i || t)
        }
        ,
        g
}),
    $(document).ready(function () {
        function e(e) {
            e || (e = 2),
                2 == e ? ($(".ts-userIpProxy-div").css("display", "none"),
                    $("#ipProxyConfigId").val(0)) : 5 == e && $(".ts-userIpProxy-div").css("display", "block")
        }

        function t() {
            doAjaxCallBack("/crawlConfig/getUserIpProxyOptions", {
                taskId: taskId
            }, i)
        }

        function i(t) {
            $("#ipProxyConfigId").html("");
            var i = "";
            if (i += n(0, "选择自有IP代理"),
            1 == t.rs) {
                var a = t.data;
                a && (a.ipProxyOpionts && (i += a.ipProxyOpionts),
                    checkRadio("ipProxy", a.ipProxy),
                    e(a.ipProxy),
                    $("#pageEncoding").val(a.pageEncoding),
                    $("#userAgent").val(a.userAgent),
                a.runConfig && $("#cookies").val(a.runConfig.cookies))
            } else
                bootbox.alert(t.msg);
            $("#ipProxyConfigId").html(i)
        }

        function n(e, t) {
            return '<option value="' + e + '">' + t + "</option>"
        }

        function a() {
            if (5 == getCheckRadio("ipProxy") && str2Num($("#ipProxyConfigId").val()) <= 0)
                return bootbox.alert("请选择自有IP代理，如无可选，请点击‘配置代理’添加！"),
                    !1;
            doAjaxCallBack("/task/saveTaskConfig", {
                taskId: taskId,
                pageEncoding: $("#pageEncoding").val(),
                userAgent: $("#userAgent").val(),
                cookies: $("#cookies").val(),
                ipProxy: getCheckRadio("ipProxy"),
                ipProxyConfigId: $("#ipProxyConfigId").val()
            }, o, "post")
        }

        function o(e) {
            1 == e.rs ? showSaveSuc() : bootbox.alert(e.msg)
        }

        $("#startTask-modal").on("shown.bs.modal", function () {
            t()
        }),
            $("input[name=ipProxy]").on("change", function () {
                e(getCheckRadio("ipProxy"))
            }),
            $(".ts-show-askConfig-modal").on("click", function () {
                $("#taskConfig-modal").modal("show"),
                    t()
            }),
            $(".ts-reload-taskConfig").on("click", function () {
                t()
            }),
            $(".ts-save-TaskConfig").on("click", function () {
                a()
            }),
            $(".ts-userAgent-baidu").on("click", function () {
                $("#userAgent").val("Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)")
            }),
            $(".ts-userAgent-google").on("click", function () {
                $("#userAgent").val("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
            }),
            $(".ts-userAgent-firefox").on("click", function () {
                $("#userAgent").val("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0")
            }),
            $(".ts-userAgent-chrome").on("click", function () {
                $("#userAgent").val("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
            }),
            $(".ts-userAgent-shouji").on("click", function () {
                $("#userAgent").val("Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36")
            }),
            $(".ts-userAgent-random").on("click", function () {
                $("#userAgent").val("")
            }), $("#expand-ele").on("click", function () {
            var bottom = $(".ins-expand-panel").css("bottom");
            if (bottom == "0px") {
                var height = $(".ins-expand-panel").css("height");
                $(".ins-expand-panel").css("bottom", (parseInt(height) * -1 + 6) + "px");
                $(".down").html('<line x1="28" y1="18" x2="34" y2="12"></line><line x1="22" y1="12" x2="28" y2="18"></line>');
            } else {
                var height = $(".ins-expand-panel").css("height");
                $(".ins-expand-panel").css("bottom", "0px");
                $(".down").html('<line x1="22" y1="18" x2="28" y2="12"></line><line x1="28" y1="12" x2="34" y2="18"></line>');
            }
        })
    });

/**获取数据结果，并放入预览表中**/
function showToAllFieldsDataTable() {
    removeAllFieldsDataTable();
    if (allFieldConfigs.length == 0) {
        return;
    }
    // 获取所有字段数据
    $("#all-fields-data-table>thead").append("<tr></tr>")
    $("#all-fields-data-table>thead tr").append("<td>lineNumber</td>")
    var fieldDatas = {};
    var maxLength = 0;
    var maxFieldConfigId;
    for (var fieldConfigId in allFieldConfigs) {
        var fieldConfig = allFieldConfigs[fieldConfigId];
        // 增加列名
        $("#all-fields-data-table>thead tr").append(genTdData(fieldConfig.name))
        fieldDatas[fieldConfig.id] = genFinalDatas(fieldConfig.selectors, fieldConfig);
        // 获取数量最多的数据结果数量
        if (fieldDatas[fieldConfig.id].length >= maxLength) {
            maxLength = fieldDatas[fieldConfig.id].length;
            maxFieldConfigId = fieldConfig.id;
        }
    }

    for (var t = 0; t < fieldDatas[maxFieldConfigId].length; t++) {
        $("#all-fields-data-table>tbody").append("<tr></tr>")
        $("#all-fields-data-table>tbody tr:last").append(genTdData("" + (t + 1)));
        for (var fieldConfigId in allFieldConfigs) {
            var fieldConfig = allFieldConfigs[fieldConfigId];
            if (fieldDatas[fieldConfig.id].length >= (t + 1)) {
                $("#all-fields-data-table>tbody tr:last").append(genTdData(fieldDatas[fieldConfig.id][t]))
            } else {
                $("#all-fields-data-table>tbody tr:last").append(genTdData(""))
            }
        }
    }
}

function genTdData(name) {
    return "<td class='layui-table-cell'>" + name + "</td>"
}

function removeAllFieldsDataTable() {
    var e = $("#all-fields-data-table>thead");
    e[0] && e.empty()
    e = $("#all-fields-data-table>tbody");
    e[0] && e.empty()
}

